diff --git a/Cargo.lock b/Cargo.lock index 90ca6b0c..821f05cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1321,6 +1321,33 @@ dependencies = [ "libloading 0.9.1", ] +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "daachorse" version = "3.0.3" @@ -1649,6 +1676,28 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2 0.11.1", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.19.0" @@ -1855,6 +1904,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "filedescriptor" version = "0.8.3" @@ -5144,6 +5199,12 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" + [[package]] name = "simd-adler32" version = "0.3.10" @@ -5251,6 +5312,7 @@ dependencies = [ "anyhow", "clap", "dirs", + "hex", "reqwest 0.13.5", "serde", "serde_json", @@ -5267,6 +5329,7 @@ dependencies = [ "skippy-model-hf", "skippy-native-runtime", "skippy-protocol", + "skippy-receipt-audit", "skippy-runtime", "skippy-runtime-install", "skippy-serving", @@ -5286,6 +5349,7 @@ dependencies = [ "crossterm", "futures", "hex", + "rand 0.10.4", "ratatui", "reqwest 0.13.5", "rustyline", @@ -5304,6 +5368,8 @@ dependencies = [ "skippy-model-resolver", "skippy-package-format", "skippy-protocol", + "skippy-receipt-audit", + "skippy-receipts", "skippy-runtime-install", "skippy-topology", "tabwriter", @@ -5441,6 +5507,7 @@ dependencies = [ "base64 0.22.1", "futures-core", "futures-util", + "hex", "http-body", "http-body-util", "serde", @@ -5628,6 +5695,43 @@ dependencies = [ "skippy-runtime", ] +[[package]] +name = "skippy-receipt-audit" +version = "0.80.0" +dependencies = [ + "anyhow", + "hex", + "rand 0.10.4", + "reqwest 0.13.5", + "serde", + "serde_json", + "sha2 0.11.1", + "skippy-model-artifact", + "skippy-model-hf", + "skippy-model-ref", + "skippy-receipts", + "skippy-runtime", + "tempfile", +] + +[[package]] +name = "skippy-receipts" +version = "0.80.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "blake3", + "curve25519-dalek", + "ed25519-dalek", + "half", + "hex", + "rand 0.10.4", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", +] + [[package]] name = "skippy-runtime" version = "0.80.0" @@ -5692,9 +5796,13 @@ dependencies = [ "axum", "base64 0.23.1", "blake3", + "ed25519-dalek", "futures-util", + "hex", "libc", "opentelemetry-proto", + "rand 0.10.4", + "reqwest 0.13.5", "serde", "serde_json", "sha2 0.11.1", @@ -5707,6 +5815,7 @@ dependencies = [ "skippy-model-artifact", "skippy-package-format", "skippy-protocol", + "skippy-receipts", "skippy-runtime", "skippy-scheduler", "skippy-tokenizer", diff --git a/Justfile b/Justfile index c7954141..76e75c84 100644 --- a/Justfile +++ b/Justfile @@ -142,6 +142,11 @@ native-full-replay backend="cpu": llama-prepare cache-reuse-smoke base_url model prompt_file output wave="4": @cargo run --locked -p skippy-correctness -- open-ai-cache-reuse --base-url "{{ base_url }}" --model "{{ model }}" --prompt-file "{{ prompt_file }}" --wave "{{ wave }}" > "{{ output }}" +# Explicit hardware capture; never part of the offline/default test suite. +receipts-metal-build: llama-prepare + cmake -S evals/receipts-metal -B target/receipts-metal -G Ninja -DCMAKE_BUILD_TYPE=Release -DNATIVE_SOURCE="$(cd '{{llama_dir}}' && pwd)" + cmake --build target/receipts-metal --parallel 8 + kv-matrix-build native_lib_dir: llama-prepare #!/usr/bin/env bash set -euo pipefail diff --git a/crates/skippy-api/src/execution/model.rs b/crates/skippy-api/src/execution/model.rs index 1001ecc1..beb5b88e 100644 --- a/crates/skippy-api/src/execution/model.rs +++ b/crates/skippy-api/src/execution/model.rs @@ -204,6 +204,7 @@ pub(super) fn model_request( telemetry_queue_capacity: 0, telemetry_level: telemetry.level, session_lifecycle_observer: None, + receipts: None, }, openai, open_events: ModelOpenEvents::Disabled, diff --git a/crates/skippy-api/src/execution/split.rs b/crates/skippy-api/src/execution/split.rs index 310e32e1..99359128 100644 --- a/crates/skippy-api/src/execution/split.rs +++ b/crates/skippy-api/src/execution/split.rs @@ -169,6 +169,7 @@ fn worker_options( ) -> Result { let config = plan.worker.clone(); Ok(BinaryStageOptions { + receipts: None, max_inflight: config.lane_count as usize, config, topology: Some(plan.topology.clone()), diff --git a/crates/skippy-api/src/native-recipe.json b/crates/skippy-api/src/native-recipe.json index ef07e9a8..9d2618ca 100644 --- a/crates/skippy-api/src/native-recipe.json +++ b/crates/skippy-api/src/native-recipe.json @@ -1,4 +1,4 @@ { "llama_upstream_sha": "5bacb7c868a2bc98682de15f447fc1ce17c9c49c", - "patch_queue_sha256": "fe6cef31db7cba6ce8f428a84eee1a816d870135cf182b0f4027b0763f8dbe37" + "patch_queue_sha256": "e4ace1fd27d987644e56f651454f2902e08c337707286901f02ea3018b7aca5f" } \ No newline at end of file diff --git a/crates/skippy-api/src/serving/lifecycle.rs b/crates/skippy-api/src/serving/lifecycle.rs index 213d1d44..502993d3 100644 --- a/crates/skippy-api/src/serving/lifecycle.rs +++ b/crates/skippy-api/src/serving/lifecycle.rs @@ -307,6 +307,7 @@ mod tests { telemetry_queue_capacity: 0, telemetry_level: skippy_serving::telemetry::TelemetryLevel::Off, session_lifecycle_observer: None, + receipts: None, }, open_events: ModelOpenEvents::Disabled, hooks_factory: None, diff --git a/crates/skippy-api/src/serving/local.rs b/crates/skippy-api/src/serving/local.rs index 970dcfa5..ba392309 100644 --- a/crates/skippy-api/src/serving/local.rs +++ b/crates/skippy-api/src/serving/local.rs @@ -210,6 +210,7 @@ impl LocalOpenAiOptions { telemetry_queue_capacity: self.telemetry_queue_capacity, telemetry_level: self.telemetry_level, session_lifecycle_observer: None, + receipts: None, }, openai, open_events, diff --git a/crates/skippy-api/tests/model_open_observer.rs b/crates/skippy-api/tests/model_open_observer.rs index 94f3c874..f77d9bbf 100644 --- a/crates/skippy-api/tests/model_open_observer.rs +++ b/crates/skippy-api/tests/model_open_observer.rs @@ -56,6 +56,7 @@ fn observed_request(config: StageConfig) -> (ModelLoadRequest, Receiver &'static str { Command::Models { .. } => "models", Command::PlanSplit(_) => "plan_split", Command::Runtime { .. } => "runtime", + Command::AuditReceipt(_) => "audit_receipt", + Command::RecheckReceipt(_) => "recheck_receipt", Command::Analytics { .. } => "analytics", } } diff --git a/crates/skippy-cli/src/cli.rs b/crates/skippy-cli/src/cli.rs index cfb11d47..4f3cebac 100644 --- a/crates/skippy-cli/src/cli.rs +++ b/crates/skippy-cli/src/cli.rs @@ -86,6 +86,10 @@ pub enum Command { }, /// Plan and admit a direct GGUF split for explicit worker endpoints. PlanSplit(PlanSplitArgs), + /// Send a chat request to a node serving with receipts, then audit the receipt. + AuditReceipt(crate::receipts::AuditReceiptArgs), + /// Check an audit's evidence again from the file and the claimed GGUF alone. + RecheckReceipt(crate::receipts::RecheckReceiptArgs), /// List, install, remove, or prune verified native runtime bundles. Runtime { #[command(subcommand)] @@ -160,6 +164,8 @@ pub struct ServeBinaryArgs { pub worker_only: bool, #[arg(skip)] pub api_bind_addr: Option, + #[command(flatten)] + pub receipts: crate::receipts::ServeReceiptsArgs, #[arg(long, default_value_t = 4)] pub max_inflight: usize, #[arg(long)] diff --git a/crates/skippy-cli/src/conversion.rs b/crates/skippy-cli/src/conversion.rs index 4a063990..f62bf1d3 100644 --- a/crates/skippy-cli/src/conversion.rs +++ b/crates/skippy-cli/src/conversion.rs @@ -128,6 +128,7 @@ pub fn binary_stage_options(args: ServeBinaryArgs) -> Result native_mtp_min_tokens: openai_speculative.native_mtp.min_draft_tokens, speculative: openai_speculative, }); + let receipts = args.receipts.stage_options(&config.model_id)?; let native_mtp_enabled = config.native_mtp_enabled; Ok(BinaryStageOptions { tuning: tuning.clone(), @@ -154,6 +155,7 @@ pub fn binary_stage_options(args: ServeBinaryArgs) -> Result split_dflash: None, openai, l3_manager: None, + receipts, }) } diff --git a/crates/skippy-cli/src/main.rs b/crates/skippy-cli/src/main.rs index 8a50d6d5..43c1365e 100644 --- a/crates/skippy-cli/src/main.rs +++ b/crates/skippy-cli/src/main.rs @@ -11,6 +11,7 @@ mod managed; mod model_source; mod multi_model; mod native_logging; +mod receipts; mod residency; mod runtime; mod serve; @@ -74,7 +75,8 @@ fn run_application(cli: Cli, startup_warnings: Vec) -> std::process::Exi Err(error) => { native_logs.flush_on_error(); let _ = skippy_commands::console::failure(&error); - std::process::ExitCode::FAILURE + // a receipt audit that did not pass names its own exit code + receipts::audit_exit_code(&error).unwrap_or(std::process::ExitCode::FAILURE) } } } @@ -144,7 +146,10 @@ async fn run_command(cli: Cli, native_logs: Arc tuning::run_trial(input).await, Command::Models { command } => skippy_commands::models::run_standalone(&command).await, Command::PlanSplit(args) => skippy_commands::split::run(args.into()), + Command::AuditReceipt(args) => receipts::audit(args).await, + Command::RecheckReceipt(args) => receipts::recheck(args).await, Command::Runtime { command } => { skippy_commands::runtime::run( command.into(), diff --git a/crates/skippy-cli/src/receipts.rs b/crates/skippy-cli/src/receipts.rs new file mode 100644 index 00000000..0b76ca5f --- /dev/null +++ b/crates/skippy-cli/src/receipts.rs @@ -0,0 +1,309 @@ +//! The receipts surface of the Skippy CLI: the receipts flags of `serve` +//! and how they become a stage's receipts options, and the `audit-receipt` +//! and `recheck-receipt` commands. + +use std::{net::SocketAddr, path::PathBuf}; + +use anyhow::{Context, Result}; +use clap::Parser; +use skippy_serving::receipts::ReceiptsOptions; + +/// The receipts flags of `serve`. +#[derive(clap::Args)] +pub struct ServeReceiptsArgs { + /// Issue verifiable inference receipts but serve no receipts API: a + /// later stage, which the stage before it reaches over the stage + /// connection. Opt-in: every weight matmul is recorded. + #[arg(long, group = "receipts_on")] + pub receipts: bool, + /// Issue receipts and serve the receipts API on this address. Opt-in: + /// every weight matmul is recorded. + #[arg(long, group = "receipts_on")] + pub receipts_listen: Option, + /// Allow a non-loopback --receipts-listen address. Openings carry + /// activations derived from prompts, so only expose them to auditors you + /// trust. + #[arg(long, requires = "receipts_on")] + pub receipts_allow_remote: bool, + /// Receipts API of the next stage, for example http://127.0.0.1:9502. + /// Without it, receipts reach the next stage over the stage connection. + #[arg(long, requires = "receipts_on")] + pub receipts_downstream: Option, + /// Model named in receipts. Defaults to the stage model id. + #[arg(long, requires = "receipts_on")] + pub receipts_claimed_model: Option, + /// File holding the hex Ed25519 seed that signs receipts. Without it, + /// the stage signs with a key made at startup. + #[arg(long, requires = "receipts_on")] + pub receipts_signing_key: Option, +} + +impl ServeReceiptsArgs { + /// The receipts options of a binary stage that serves `model_id`, when + /// the flags turn receipts on. + pub fn stage_options(&self, model_id: &str) -> Result> { + let signing_key = self + .receipts_signing_key + .as_deref() + .map(read_signing_key) + .transpose()?; + Ok( + (self.receipts || self.receipts_listen.is_some()).then(|| ReceiptsOptions { + listen: self.receipts_listen, + allow_remote: self.receipts_allow_remote, + downstream: self.receipts_downstream.clone(), + claimed_model: self + .receipts_claimed_model + .clone() + .unwrap_or_else(|| model_id.to_owned()), + signing_key, + }), + ) + } +} + +/// A receipts signing key file: 64 hex digits, the Ed25519 seed. +fn read_signing_key(path: &std::path::Path) -> Result<[u8; 32]> { + let text = std::fs::read_to_string(path) + .with_context(|| format!("read receipts signing key {}", path.display()))?; + let bytes = + hex::decode(text.trim()).with_context(|| format!("{} is not hex", path.display()))?; + <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| { + anyhow::anyhow!( + "{} holds {} bytes; an Ed25519 seed has 32", + path.display(), + bytes.len() + ) + }) +} + +/// A receipts setting of `serve`: `receipts` itself or one of its +/// `receipts-` options. They all need a binary stage. +pub fn is_serve_setting(name: &str) -> bool { + name == "receipts" || name.starts_with("receipts-") +} + +#[derive(Parser)] +pub struct AuditReceiptArgs { + /// OpenAI base URL of stage 0. + #[arg(long, default_value = "http://127.0.0.1:9337")] + pub api: String, + /// Receipts API of stage 0. Without it the audit opens the receipt on + /// the OpenAI API, which a Mesh node serves. + #[arg(long)] + pub receipts: Option, + /// The GGUF the node claims to serve: a file here, or + /// `repo@revision/file` on Hugging Face, which the audit reads by range + /// without downloading the model. + #[arg(long)] + pub claimed_model: PathBuf, + /// The model id the chat request names. Without it, the first model + /// the node lists. A Mesh node lists its router first, so name the + /// served model there. + #[arg(long)] + pub model: Option, + #[arg(long, default_value = "Explain in two sentences why the sky is blue.")] + pub prompt: String, + #[arg(long, default_value_t = 32)] + pub max_tokens: u32, + /// Challenge this layer alone instead of random ones. + #[arg(long)] + pub layer: Option, + /// Times to compute each challenged layer for the client cost report. + #[arg(long, default_value_t = 1)] + pub timing_runs: u32, + /// Write the audit's evidence to this file, for `recheck-receipt`. + #[arg(long, conflicts_with = "layer")] + pub evidence: Option, + /// Sample at this temperature. At 0 the node decodes greedily. Above 0 + /// the audit sets a seed and replays the draw of each checked token. + #[arg(long, default_value_t = 0.0)] + pub temperature: f64, + /// Top-p of a sampled turn. Without it the node's default applies. + #[arg(long, requires = "temperature")] + pub top_p: Option, + /// Top-k of a sampled turn. Without it the node's default applies. + #[arg(long, requires = "temperature")] + pub top_k: Option, + /// Min-p of a sampled turn. Without it the node's default applies. + #[arg(long, requires = "temperature")] + pub min_p: Option, + /// Seed of a sampled turn, above 0. Without it the audit picks one. + #[arg(long, requires = "temperature")] + pub seed: Option, + /// Reasoning tokens to allow a thinking model. The node forces the end + /// of the reasoning when they run out, and the audit replays which + /// tokens it forced. Without it the model reasons without a limit. + #[arg(long)] + pub reasoning_budget: Option, +} + +#[derive(Parser)] +pub struct RecheckReceiptArgs { + /// Evidence that `audit-receipt --evidence` wrote. + #[arg(long)] + pub evidence: PathBuf, + /// The GGUF the receipt claims: a file here, or `repo@revision/file` + /// on Hugging Face. Defaults to the model the receipt names when that + /// is a Hugging Face file. + #[arg(long)] + pub claimed_model: Option, +} + +impl From for skippy_commands::receipts::RecheckReceiptCommand { + fn from(args: RecheckReceiptArgs) -> Self { + Self { + evidence: args.evidence, + claimed_model: args.claimed_model, + } + } +} + +impl From for skippy_commands::receipts::AuditReceiptCommand { + fn from(args: AuditReceiptArgs) -> Self { + Self { + api: args.api, + receipts: args.receipts, + claimed_model: args.claimed_model, + model: args.model, + prompt: args.prompt, + max_tokens: args.max_tokens, + layer: args.layer, + timing_runs: args.timing_runs.max(1), + evidence: args.evidence, + sampling: skippy_commands::receipts::AuditSampling { + temperature: args.temperature, + top_p: args.top_p, + top_k: args.top_k, + min_p: args.min_p, + seed: args.seed, + reasoning_budget: args.reasoning_budget, + }, + } + } +} + +/// Runs `audit-receipt`. +pub async fn audit(args: AuditReceiptArgs) -> Result<()> { + let command: skippy_commands::receipts::AuditReceiptCommand = args.into(); + tokio::task::spawn_blocking(move || { + skippy_commands::receipts::run( + command, + &skippy_receipt_audit::native_model::load_claimed_model, + ) + }) + .await? +} + +/// Runs `recheck-receipt`. +pub async fn recheck(args: RecheckReceiptArgs) -> Result<()> { + let command: skippy_commands::receipts::RecheckReceiptCommand = args.into(); + tokio::task::spawn_blocking(move || { + skippy_commands::receipts::recheck( + command, + &skippy_receipt_audit::native_model::load_claimed_model, + ) + }) + .await? +} + +/// The exit code a failed command names when it is a receipt audit that did +/// not pass: 1 failed, 2 not audited, 3 the node did not answer. +pub fn audit_exit_code(error: &anyhow::Error) -> Option { + skippy_commands::receipts::exit_code(error).map(std::process::ExitCode::from) +} + +#[cfg(test)] +mod tests { + use clap::Parser; + + use crate::cli::{Cli, Command}; + + #[test] + fn a_later_stage_issues_receipts_without_an_api() { + let parse = |flags: &[&str]| { + let mut args = vec![ + "skippy", + "serve", + "--config", + "stage.json", + "--stage-transport", + "binary", + ]; + args.extend_from_slice(flags); + Cli::try_parse_from(args) + }; + + let cli = parse(&["--receipts", "--receipts-claimed-model", "m"]).expect("parse"); + let Command::Serve(args) = cli.command else { + panic!("expected serve command"); + }; + let receipts = args + .stage + .receipts + .stage_options("stage-model") + .expect("resolve receipts options") + .expect("receipts on"); + assert_eq!(receipts.listen, None); + assert_eq!(receipts.downstream, None); + assert_eq!(receipts.claimed_model, "m"); + + assert!(parse(&["--receipts-claimed-model", "m"]).is_err()); + assert!(parse(&["--receipts", "--receipts-listen", "127.0.0.1:9501"]).is_err()); + } + + #[test] + fn audit_receipt_samples_only_with_a_temperature() { + let parse = |flags: &[&str]| { + let mut args = vec!["skippy", "audit-receipt", "--claimed-model", "m.gguf"]; + args.extend_from_slice(flags); + Cli::try_parse_from(args).map(|cli| { + let Command::AuditReceipt(args) = cli.command else { + panic!("expected audit-receipt"); + }; + skippy_commands::receipts::AuditReceiptCommand::from(args).sampling + }) + }; + // greedy by default + let greedy = parse(&[]).expect("parse"); + assert_eq!(greedy, skippy_commands::receipts::AuditSampling::default()); + let sampled = parse(&[ + "--temperature", + "0.7", + "--top-p", + "0.95", + "--top-k", + "40", + "--min-p", + "0.05", + "--seed", + "1234", + ]) + .expect("parse"); + assert_eq!( + sampled, + skippy_commands::receipts::AuditSampling { + temperature: 0.7, + top_p: Some(0.95), + top_k: Some(40), + min_p: Some(0.05), + seed: Some(1234), + reasoning_budget: None, + } + ); + // a reasoning budget goes with a greedy turn as well + let budgeted = parse(&["--reasoning-budget", "64"]).expect("parse"); + assert_eq!(budgeted.reasoning_budget, Some(64)); + assert!(parse(&["--reasoning-budget", "-1"]).is_err()); + // a filter or a seed means nothing to a greedy turn + for flags in [ + ["--top-k", "40"], + ["--top-p", "0.9"], + ["--min-p", "0.1"], + ["--seed", "7"], + ] { + assert!(parse(&flags).is_err(), "{flags:?}"); + } + assert!(parse(&["--temperature", "0.7", "--seed", "-1"]).is_err()); + } +} diff --git a/crates/skippy-cli/src/serve_settings/mod.rs b/crates/skippy-cli/src/serve_settings/mod.rs index fd6cfd69..59edbea5 100644 --- a/crates/skippy-cli/src/serve_settings/mod.rs +++ b/crates/skippy-cli/src/serve_settings/mod.rs @@ -466,6 +466,9 @@ pub fn section(name: &str) -> &'static str { if name.starts_with("downstream-wire-") { return "network"; } + if crate::receipts::is_serve_setting(name) { + return "distributed"; + } if name.contains("speculative") || name.starts_with("draft-") || name.starts_with("native-mtp-") { return "speculative"; diff --git a/crates/skippy-cli/src/serve_settings/resolution.rs b/crates/skippy-cli/src/serve_settings/resolution.rs index f2cde875..d5d7d027 100644 --- a/crates/skippy-cli/src/serve_settings/resolution.rs +++ b/crates/skippy-cli/src/serve_settings/resolution.rs @@ -20,6 +20,7 @@ impl ServeSettings { let section = super::section(name); if args.stage_transport.is_none() && (section == "network" + || crate::receipts::is_serve_setting(name) || matches!( name.as_str(), "activation-codec" diff --git a/crates/skippy-cli/src/serve_settings/tests.rs b/crates/skippy-cli/src/serve_settings/tests.rs index 1a29acd3..15e6ec90 100644 --- a/crates/skippy-cli/src/serve_settings/tests.rs +++ b/crates/skippy-cli/src/serve_settings/tests.rs @@ -1094,3 +1094,56 @@ fn documented_example_is_a_valid_complete_settings_file() { ); } } + +#[test] +fn receipts_flags_are_binary_stage_settings() { + assert_eq!(section("receipts-listen"), "distributed"); + assert_eq!(section("receipts"), "distributed"); + let Command::Serve(args) = parse_test(&[ + "skippy", + "serve", + "--model", + "missing.gguf", + "--receipts-listen", + "127.0.0.1:9501", + ]) + .unwrap() + .command + else { + panic!() + }; + assert!( + args.public + .settings + .validate_mode(&args) + .unwrap_err() + .to_string() + .contains("--receipts-listen requires --stage-transport binary") + ); + // the bare flag is the same setting without an API + let Command::Serve(args) = + parse_test(&["skippy", "serve", "--model", "missing.gguf", "--receipts"]) + .unwrap() + .command + else { + panic!() + }; + assert!( + args.public + .settings + .validate_mode(&args) + .unwrap_err() + .to_string() + .contains("--receipts requires --stage-transport binary") + ); + assert!( + parse_test(&[ + "skippy", + "serve", + "--model", + "missing.gguf", + "--receipts-allow-remote", + ]) + .is_err() + ); +} diff --git a/crates/skippy-commands/Cargo.toml b/crates/skippy-commands/Cargo.toml index 922aeec8..07985245 100644 --- a/crates/skippy-commands/Cargo.toml +++ b/crates/skippy-commands/Cargo.toml @@ -37,6 +37,9 @@ skippy-package-format = { path = "../skippy-package-format", version = "0.80.0" skippy-api = { path = "../skippy-api", version = "0.80.0" } skippy-events = { path = "../skippy-events", version = "0.80.0" } skippy-protocol = { path = "../skippy-protocol", version = "0.80.0" } +skippy-receipt-audit = { path = "../skippy-receipt-audit", version = "0.80.0" } +skippy-receipts = { path = "../skippy-receipts", version = "0.80.0" } +rand = "0.10" skippy-runtime-install = { path = "../skippy-runtime-install", version = "0.80.0" } skippy-topology = { path = "../skippy-topology", version = "0.80.0" } tokio = { version = "1", features = ["rt", "time", "macros", "fs"] } diff --git a/crates/skippy-commands/README.md b/crates/skippy-commands/README.md index 603945a1..6b3c484a 100644 --- a/crates/skippy-commands/README.md +++ b/crates/skippy-commands/README.md @@ -8,6 +8,12 @@ Skippy command execution and output formatting. This crate owns the `models` arg interactive chat or raw-completion client. It does not load a native runtime or manage stage processes. +`receipts` runs `skippy audit-receipt` and `skippy recheck-receipt`. It sends +the chat request, opens the challenge on the node over HTTP, writes the +evidence file, prints the report, and ends with the exit code of the outcome. +The audit itself is in [`skippy-receipt-audit`](../skippy-receipt-audit/README.md), +which the Mesh host also uses. + Responses stream as they arrive. After each response, a single-line emoji footer shows generation speed, time to first token (TTFT), total elapsed time, input and output token counts, and cached input tokens with their reuse percentage. The diff --git a/crates/skippy-commands/src/lib.rs b/crates/skippy-commands/src/lib.rs index b1efdb6c..406fd01b 100644 --- a/crates/skippy-commands/src/lib.rs +++ b/crates/skippy-commands/src/lib.rs @@ -8,5 +8,6 @@ pub mod console; pub mod models; pub mod prompt; +pub mod receipts; pub mod runtime; pub mod split; diff --git a/crates/skippy-commands/src/receipts.rs b/crates/skippy-commands/src/receipts.rs new file mode 100644 index 00000000..fa0e783e --- /dev/null +++ b/crates/skippy-commands/src/receipts.rs @@ -0,0 +1,401 @@ +//! `skippy audit-receipt`: sends one chat request to a node serving with +//! receipts, then challenges the receipt and checks the opening against the +//! claimed GGUF on this machine. +//! +//! The request names a fresh VRF key, so the node binds the receipt to it +//! and signs the turn root. The challenge comes from the VRF of that root, +//! and the checked rows from the VRF of the opening as received, so +//! neither the node nor this client chooses them. +//! +//! The checks, in order: the receipt is bound to this client's key and +//! signed, covers every layer of the claimed model, and does not contradict +//! the request; the opening holds exactly what the challenge asks, every +//! opened leaf is in its stage tree, stages agree where they hand over, +//! and every opened value fits the claimed model; each picked layer's glue +//! computed on the opened values, and its weight rows; the input of layer +//! 0 is what the receipt's tokens make; the token sampled at each head +//! position is the greedy choice of the claimed output head on the opened +//! final residual, or with `--temperature` the token the draw of the +//! request's seed picks; the response is the text of the tokens the receipt says +//! were sampled; and each picked attention head's partials combine to its +//! opened output, and recompute, for blocks this client draws after the +//! opening, from the K and V rows the node opens. +//! +//! The report ends with one of four lines, and the command with the exit +//! code that goes with it ([`Outcome`]): `AUDIT PASS` (0), `AUDIT FAIL` +//! (1), `NO AUDIT` (2) when this machine could not run a check, and +//! `NO ANSWER` (3) when the node gave no usable signed answer to the +//! challenge. +//! +//! The audit itself is [`skippy_receipt_audit`]'s. This module sends the +//! request, opens the challenge over HTTP, keeps the evidence file, and +//! prints the report. +//! +//! [`Outcome`]: skippy_receipt_audit::outcome::Outcome + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use reqwest::StatusCode; +use skippy_receipt_audit::chat_reply::ChatReply; +use skippy_receipt_audit::claimed_file; +use skippy_receipt_audit::claimed_model::LoadClaimedModel; +use skippy_receipt_audit::output::NoAuditOutput; +use skippy_receipt_audit::report_text; +use skippy_receipt_audit::turn_audit::{ + self, AuditOptions, ClaimedSetup, OpenChallenge, Opened, OpenedRows, ReceivedTurn, TurnAudit, +}; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::turn; +use skippy_receipts::vrf; +use skippy_receipts::wire::{Challenge, Receipt}; + +/// How long to wait for a turn's receipt after its response. +const RECEIPT_WAIT: Duration = Duration::from_secs(10); + +pub struct AuditReceiptCommand { + /// OpenAI base URL of stage 0, for example `http://127.0.0.1:9337`. + pub api: String, + /// Receipts API of stage 0, for example `http://127.0.0.1:9501`. Without + /// it the audit takes the receipt from the response and opens it on the + /// OpenAI API (`POST /v1/receipts/open`), as a client of a Mesh node does. + pub receipts: Option, + /// The GGUF the node claims to serve. + pub claimed_model: PathBuf, + /// The model id the chat request names. Without it, the first model + /// the node lists. + pub model: Option, + pub prompt: String, + pub max_tokens: u32, + /// Challenge this layer alone instead of random ones. + pub layer: Option, + /// Times to compute each challenged layer for the cost report; the + /// checks use the first. + pub timing_runs: u32, + /// Where to write the audit's evidence, which `recheck` checks again. + pub evidence: Option, + /// How the request asks the node to choose its tokens. + pub sampling: AuditSampling, +} + +/// Where the audit opens its challenge. +enum OpenRoute { + /// A stage's receipts API. + ReceiptsApi(String), + /// The OpenAI API, for a bound receipt. The body names the model, and + /// `x-mesh-target` the node key, so a Mesh node routes the challenge to + /// the peer that signed the receipt; a plain node ignores both. + OpenAi { + api: String, + model: String, + node_key: Option, + }, +} + +/// Audits one turn, prints the report, and ends with the audit's outcome: +/// `Ok` for a pass, else an error that carries the outcome's exit code +/// ([`exit_code`]): 1 for a failed audit, 2 for no audit, 3 for a node +/// that did not answer the challenge. +/// +/// Whatever keeps this machine from auditing is no audit: the claimed GGUF +/// cannot be opened, the node cannot be reached for the request, or its +/// response carries no receipt. None of them is a failed audit. +pub fn run(command: AuditReceiptCommand, load: LoadClaimedModel<'_>) -> Result<()> { + let evidence = command.evidence.clone(); + let audit = audit(command, load) + .unwrap_or_else(|error| TurnAudit::NoAudit(NoAuditOutput::new("", format!("{error:#}")))); + conclude(audit, evidence.as_deref()) +} + +/// Prints an audit's report, keeps its evidence at `evidence`, and ends +/// with its outcome. +fn conclude(audit: TurnAudit, evidence: Option<&std::path::Path>) -> Result<()> { + let outcome = audit.outcome(); + let reason = match &audit { + TurnAudit::NoAudit(output) => { + crate::console::present(output, |out| report_text::render_no_audit(out, output))?; + output.reason.clone() + } + TurnAudit::Unanswered(output) => { + crate::console::present(output, |out| report_text::render_unanswered(out, output))?; + output.reason.clone() + } + TurnAudit::Audited { + output, + evidence: kept, + } => { + if let (Some(path), Some(kept)) = (evidence, kept) { + std::fs::write(path, serde_json::to_vec_pretty(kept)?) + .with_context(|| format!("write evidence {}", path.display()))?; + } + crate::console::present(&**output, |out| report_text::render(out, output))?; + let mut reasons = output.failures(); + if reasons.is_empty() { + reasons = output.unchecked(); + } + reasons.join("; ") + } + }; + AuditExit::result(outcome, reason) +} + +/// Sends the request and audits the turn. An error is this machine's or +/// the request's: nothing was audited. +fn audit(command: AuditReceiptCommand, load: LoadClaimedModel<'_>) -> Result { + let setup = ClaimedSetup::open( + &command.claimed_model, + &claimed_file::default_cache_root()?, + load, + )?; + let client = reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(600)) + .build()?; + let receipt_id = uuid::Uuid::new_v4().hyphenated().to_string(); + // a fresh key per audit: the node binds it before the client sees the root + let key = vrf::SecretKey::generate(&mut rand::rng()); + let sampling = command.sampling.with_seed(); + let (response, carried) = chat(&client, &command, &sampling, &receipt_id, &key)?; + let receipts = command + .receipts + .as_deref() + .map(|url| url.trim_end_matches('/')); + // a node that predates the receipt in the response body serves it only + // from its receipts API + let receipt = match (carried, receipts) { + (Some(receipt), _) => receipt, + (None, Some(receipts)) => fetch_receipt(&client, receipts, &receipt_id)?, + (None, None) => bail!( + "the response carried no receipt; pass --receipts to fetch it from the node's receipts API" + ), + }; + let route = match receipts { + Some(receipts) => OpenRoute::ReceiptsApi(receipts.to_owned()), + None => OpenRoute::OpenAi { + api: command.api.trim_end_matches('/').to_owned(), + model: response.model.clone(), + node_key: receipt.binding.as_ref().map(|b| b.node_key.clone()), + }, + }; + let opener = HttpOpener { + client: &client, + route, + }; + let turn = ReceivedTurn { + receipt, + key: &key, + response: Some((&command.prompt, &response)), + // what `chat` sent + sampling: sampling.requested(), + asked_id: Some(&receipt_id), + }; + let options = AuditOptions { + layer: command.layer, + timing_runs: command.timing_runs, + }; + Ok(turn_audit::audit_turn(&setup, turn, &opener, &options)) +} + +/// Opens challenges over HTTP: on a stage's receipts API, or on the OpenAI +/// API of a node. +pub struct HttpOpener<'a> { + client: &'a reqwest::blocking::Client, + route: OpenRoute, +} + +impl OpenChallenge for HttpOpener<'_> { + fn open(&self, challenge: &Challenge) -> Result { + let started = Instant::now(); + let (opening, bytes, signature) = self.post("open", challenge)?; + Ok(Opened { + opening, + bytes, + signature, + seconds: started.elapsed().as_secs_f64(), + }) + } + + fn rows(&self, challenge: &BlockChallenge) -> Result { + let started = Instant::now(); + let (rows, bytes, signature) = self.post("rows", challenge)?; + Ok(OpenedRows { + rows, + bytes, + signature, + seconds: started.elapsed().as_secs_f64(), + }) + } +} + +impl HttpOpener<'_> { + /// Posts `body` to the route's `action` endpoint, and returns the + /// decoded answer, its bytes, and the node's signature of them. A busy + /// node is asked again ([`busy_retry`]). + fn post( + &self, + action: &str, + body: &B, + ) -> Result<(T, Vec, Option)> { + let started = Instant::now(); + let response = loop { + let response = self.request(action, body)?.send()?; + let retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()); + match busy_retry::pause(response.status(), retry_after, started.elapsed()) { + Some(pause) => std::thread::sleep(pause), + None => break response, + } + }; + let signature = response + .headers() + .get(turn::OPENING_SIGNATURE_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + let (value, bytes) = read_bytes(response)?; + Ok((value, bytes, signature)) + } + + /// The request that posts `body` to the route's `action` endpoint. + fn request( + &self, + action: &str, + body: &B, + ) -> Result { + let request = match &self.route { + OpenRoute::ReceiptsApi(receipts) => self + .client + .post(format!("{receipts}/receipts/{action}")) + .json(body), + OpenRoute::OpenAi { + api, + model, + node_key, + } => { + let mut body = serde_json::to_value(body)?; + body["model"] = model.clone().into(); + let request = self + .client + .post(format!("{api}/v1/receipts/{action}")) + .json(&body); + match node_key { + Some(key) => request.header("x-mesh-target", key), + None => request, + } + } + }; + Ok(request) + } +} + +fn chat( + client: &reqwest::blocking::Client, + command: &AuditReceiptCommand, + sampling: &AuditSampling, + receipt_id: &str, + key: &vrf::SecretKey, +) -> Result<(ChatReply, Option)> { + let api = command.api.trim_end_matches('/'); + let listed: serde_json::Value; + let model = match &command.model { + Some(model) => model.as_str(), + None => { + listed = get_json(client.get(format!("{api}/v1/models")))?; + listed["data"][0]["id"] + .as_str() + .context("the node lists no model")? + } + }; + let mut body = serde_json::json!({ + "model": model, + "messages": [{ "role": "user", "content": command.prompt }], + "max_tokens": command.max_tokens, + "stream": false, + }); + sampling.apply(&mut body); + let value: serde_json::Value = get_json( + client + .post(format!("{api}/v1/chat/completions")) + .header("x-request-id", receipt_id) + .header("x-receipt-client-key", hex::encode(key.public())) + .json(&body), + )?; + let message = &value["choices"][0]["message"]; + let text = |field: &str| message[field].as_str().unwrap_or_default().to_string(); + let receipt = match value.get("receipt") { + Some(receipt) => { + Some(serde_json::from_value(receipt.clone()).context("decode the response's receipt")?) + } + None => None, + }; + let reply = ChatReply { + model: model.to_owned(), + content: text("content"), + reasoning: text("reasoning_content"), + cut_short: value["choices"][0]["finish_reason"] == "length", + }; + Ok((reply, receipt)) +} + +/// Stage 0 commits a turn just after its response is sent, so the receipt +/// can be missing for a moment. +fn fetch_receipt( + client: &reqwest::blocking::Client, + receipts: &str, + receipt_id: &str, +) -> Result { + let deadline = Instant::now() + RECEIPT_WAIT; + loop { + let response = client + .get(format!("{receipts}/receipts/{receipt_id}")) + .send() + .with_context(|| { + format!( + "no receipts API at {receipts}: a stage that issues no receipts serves none, and says why in a warning when it starts" + ) + })?; + if response.status() != StatusCode::NOT_FOUND || Instant::now() >= deadline { + return decode(response); + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +/// The reply decoded, and its body as received. +fn read_bytes( + response: reqwest::blocking::Response, +) -> Result<(T, Vec)> { + let status = response.status(); + let body = response.bytes()?.to_vec(); + if !status.is_success() { + bail!("{status}: {}", String::from_utf8_lossy(&body)); + } + let value = serde_json::from_slice(&body) + .with_context(|| format!("decode reply: {}", String::from_utf8_lossy(&body)))?; + Ok((value, body)) +} + +fn get_json( + request: reqwest::blocking::RequestBuilder, +) -> Result { + decode(request.send()?) +} + +fn decode(response: reqwest::blocking::Response) -> Result { + let status = response.status(); + let body = response.text()?; + if !status.is_success() { + bail!("{status}: {body}"); + } + serde_json::from_str(&body).with_context(|| format!("decode reply: {body}")) +} + +mod audit_exit; +mod audit_sampling; +mod busy_retry; +mod recheck; + +pub use audit_exit::{AuditExit, exit_code}; +pub use audit_sampling::AuditSampling; +pub use recheck::{RecheckReceiptCommand, recheck}; diff --git a/crates/skippy-commands/src/receipts/audit_exit.rs b/crates/skippy-commands/src/receipts/audit_exit.rs new file mode 100644 index 00000000..9632d3e9 --- /dev/null +++ b/crates/skippy-commands/src/receipts/audit_exit.rs @@ -0,0 +1,92 @@ +//! How `skippy audit-receipt` and `skippy recheck-receipt` end: an audit +//! that did not pass is an error that carries its outcome, and the process +//! exits with the outcome's code. + +use std::fmt; + +use skippy_receipt_audit::outcome::Outcome; + +/// An audit that did not pass, as the error a command ends with. The +/// report is printed before; this carries the exit code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuditExit { + pub outcome: Outcome, + reason: String, +} + +impl AuditExit { + pub(super) fn new(outcome: Outcome, reason: impl Into) -> Self { + Self { + outcome, + reason: reason.into(), + } + } + + /// How a command ends after an audit with `outcome`: `Ok` for a pass, + /// else the error that carries the outcome's exit code. + pub(super) fn result(outcome: Outcome, reason: impl Into) -> anyhow::Result<()> { + match outcome { + Outcome::Pass => Ok(()), + outcome => Err(Self::new(outcome, reason).into()), + } + } +} + +impl fmt::Display for AuditExit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let what = match self.outcome { + Outcome::Pass => "the receipt audit passed", + Outcome::Fail => "the receipt audit failed", + Outcome::NoAudit => "the receipt was not audited", + Outcome::Unanswered => "the node did not answer the audit", + }; + if self.reason.is_empty() { + f.write_str(what) + } else { + write!(f, "{what}: {}", self.reason) + } + } +} + +impl std::error::Error for AuditExit {} + +/// The exit code of a command that ended with `error`, when the error is +/// the outcome of an audit: 1 for a failed audit, 2 for no audit, 3 for a +/// node that did not answer. `None` for any other error. +pub fn exit_code(error: &anyhow::Error) -> Option { + error + .downcast_ref::() + .map(|exit| exit.outcome.exit_code()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_command_exits_with_its_audits_outcome() { + for outcome in [Outcome::Fail, Outcome::NoAudit, Outcome::Unanswered] { + let error: anyhow::Error = AuditExit::new(outcome, "why").into(); + assert_eq!(exit_code(&error), Some(outcome.exit_code())); + // context a caller adds does not hide it + let error = error.context("audit receipt"); + assert_eq!(exit_code(&error), Some(outcome.exit_code())); + } + assert_eq!(exit_code(&anyhow::anyhow!("no such file")), None); + // a pass ends the command well; every other outcome names its code + assert!(AuditExit::result(Outcome::Pass, "").is_ok()); + for (outcome, code) in [ + (Outcome::Fail, 1), + (Outcome::NoAudit, 2), + (Outcome::Unanswered, 3), + ] { + let error = AuditExit::result(outcome, "why").unwrap_err(); + assert_eq!(exit_code(&error), Some(code)); + } + let exit = AuditExit::new(Outcome::Unanswered, "timed out"); + assert_eq!( + exit.to_string(), + "the node did not answer the audit: timed out" + ); + } +} diff --git a/crates/skippy-commands/src/receipts/audit_sampling.rs b/crates/skippy-commands/src/receipts/audit_sampling.rs new file mode 100644 index 00000000..897017f6 --- /dev/null +++ b/crates/skippy-commands/src/receipts/audit_sampling.rs @@ -0,0 +1,189 @@ +//! How `skippy audit-receipt` asks the node to choose its tokens. +//! +//! Without a temperature the request is greedy: the best logit at every +//! token, and nothing that could change the choice, which the head check +//! judges in full. With one, the node samples, and the request sets the +//! seed, so the node states a draw this client can replay with a seed it +//! did not choose. +//! +//! The request lets a thinking model reason without a limit unless it +//! names a reasoning budget. With one, the node's sampler forces the end +//! of the reasoning when the budget runs out, and the head check replays +//! which tokens it forced. + +use skippy_receipts::sampler_request::RequestedSampling; + +/// The sampling options of `skippy audit-receipt`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct AuditSampling { + /// 0 asks for greedy decoding. + pub temperature: f64, + pub top_p: Option, + pub top_k: Option, + pub min_p: Option, + /// The seed of a sampled turn. Without one the audit picks one. + pub seed: Option, + /// The reasoning tokens the request allows. Without a budget the + /// model reasons without a limit. + pub reasoning_budget: Option, +} + +impl AuditSampling { + fn sampled(&self) -> bool { + self.temperature > 0.0 + } + + /// The options with a seed for a sampled turn: the one given, else a + /// random one above 0, since a node reads seed 0 as none. + pub(super) fn with_seed(mut self) -> Self { + if self.sampled() && self.seed.is_none_or(|seed| seed == 0) { + self.seed = Some(rand::RngExt::random_range(&mut rand::rng(), 1..=u32::MAX)); + } + self + } + + /// Sets the request's sampling fields in `body`. + pub(super) fn apply(&self, body: &mut serde_json::Value) { + body["temperature"] = self.temperature.max(0.0).into(); + // a node gives a thinking model a budget of its own (half the + // tokens) when the request names none: the request always names + // what it allows, so the comparison with the statement is exact + body["reasoning_budget"] = self.requested_budget().into(); + if !self.sampled() { + return; + } + if let Some(top_p) = self.top_p { + body["top_p"] = top_p.into(); + } + if let Some(top_k) = self.top_k { + body["top_k"] = top_k.into(); + } + if let Some(min_p) = self.min_p { + body["min_p"] = min_p.into(); + } + if let Some(seed) = self.seed { + body["seed"] = seed.into(); + } + } + + /// The reasoning tokens the request allows; -1 for no limit. + fn requested_budget(&self) -> i64 { + self.reasoning_budget.map_or(-1, i64::from) + } + + /// What the request set, for the comparison with the node's sampler + /// statement. + pub(super) fn requested(&self) -> RequestedSampling { + let greedy = RequestedSampling { + reasoning_budget: Some(self.requested_budget()), + ..RequestedSampling::greedy() + }; + if !self.sampled() { + return greedy; + } + RequestedSampling { + temperature: Some(self.temperature), + top_p: self.top_p, + top_k: self.top_k, + min_p: self.min_p, + seed: self.seed.map(u64::from), + // a filter the request leaves out runs at the node's default, + // which is on for Skippy: one stated off contradicts it + unset_filters_on: Some(true), + ..greedy + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn a_request_without_a_temperature_is_greedy() { + let sampling = AuditSampling::default().with_seed(); + assert_eq!(sampling.seed, None); + let mut body = json!({}); + sampling.apply(&mut body); + assert_eq!(body, json!({ "temperature": 0.0, "reasoning_budget": -1 })); + assert_eq!(sampling.requested(), RequestedSampling::greedy()); + // filters without a temperature are not sent: the turn is greedy + let filtered = AuditSampling { + top_k: Some(40), + seed: Some(7), + ..AuditSampling::default() + }; + let mut body = json!({}); + filtered.with_seed().apply(&mut body); + assert!(body.get("top_k").is_none() && body.get("seed").is_none()); + } + + #[test] + fn a_sampled_request_sets_its_filters_and_a_seed() { + let sampling = AuditSampling { + temperature: 0.7, + top_p: Some(0.95), + top_k: Some(40), + min_p: None, + seed: None, + reasoning_budget: None, + } + .with_seed(); + let seed = sampling.seed.expect("a seed"); + assert_ne!(seed, 0); + let mut body = json!({ "model": "m" }); + sampling.apply(&mut body); + assert_eq!(body["temperature"], 0.7); + assert_eq!(body["top_p"], 0.95); + assert_eq!(body["top_k"], 40); + assert_eq!(body["seed"], seed); + assert!(body.get("min_p").is_none()); + let requested = sampling.requested(); + assert_eq!(requested.seed, Some(u64::from(seed))); + assert_eq!(requested.temperature, Some(0.7)); + assert_eq!(requested.top_k, Some(40)); + assert_eq!(requested.grammar, Some(false)); + assert_eq!(requested.reasoning_budget, Some(-1)); + assert_eq!(requested.ignore_eos, Some(false)); + assert_eq!(requested.unset_filters_on, Some(true)); + // a given seed is kept, and seed 0 is replaced + let given = AuditSampling { + seed: Some(1234), + ..sampling + }; + assert_eq!(given.with_seed().seed, Some(1234)); + let zero = AuditSampling { + seed: Some(0), + ..sampling + }; + assert_ne!(zero.with_seed().seed, Some(0)); + } + + #[test] + fn a_request_with_a_reasoning_budget_names_it() { + // greedy or sampled, the budget is sent and is what the node must state + for temperature in [0.0, 0.7] { + let sampling = AuditSampling { + temperature, + reasoning_budget: Some(64), + ..AuditSampling::default() + } + .with_seed(); + let mut body = json!({}); + sampling.apply(&mut body); + assert_eq!(body["reasoning_budget"], 64); + assert_eq!(sampling.requested().reasoning_budget, Some(64)); + } + // a budget of no tokens is a budget + let none = AuditSampling { + reasoning_budget: Some(0), + ..AuditSampling::default() + }; + let mut body = json!({}); + none.apply(&mut body); + assert_eq!(body["reasoning_budget"], 0); + assert_eq!(none.requested().reasoning_budget, Some(0)); + } +} diff --git a/crates/skippy-commands/src/receipts/busy_retry.rs b/crates/skippy-commands/src/receipts/busy_retry.rs new file mode 100644 index 00000000..c152362b --- /dev/null +++ b/crates/skippy-commands/src/receipts/busy_retry.rs @@ -0,0 +1,67 @@ +//! When a busy node is asked again. +//! +//! A stage with too many openings waiting answers 503 with a `Retry-After` +//! and admits nothing, so the same request can be sent again. The node +//! keeps a turn open for [`WINDOW`] after its receipt, so a request is sent +//! again only while the pause still ends inside that time. + +use std::time::Duration; + +use reqwest::StatusCode; + +/// How long after its first try a request is still sent again. +pub(super) const WINDOW: Duration = Duration::from_secs(10); +/// The shortest pause, whatever the node's `Retry-After` says. +const MIN_PAUSE: Duration = Duration::from_secs(1); + +/// The pause before a request is sent again: `status` and `retry_after` +/// are the node's answer, and `asked_for` is the time since the first try. +/// `None` when the answer is not a busy one, or when the pause would end +/// past the window. +pub(super) fn pause( + status: StatusCode, + retry_after: Option<&str>, + asked_for: Duration, +) -> Option { + if status != StatusCode::SERVICE_UNAVAILABLE { + return None; + } + let seconds = retry_after?.trim().parse().ok()?; + let pause = Duration::from_secs(seconds).max(MIN_PAUSE); + (asked_for + pause <= WINDOW).then_some(pause) +} + +#[cfg(test)] +mod tests { + use super::*; + + const BUSY: StatusCode = StatusCode::SERVICE_UNAVAILABLE; + + #[test] + fn a_busy_node_is_asked_again_after_the_pause_it_names() { + let two = Some(Duration::from_secs(2)); + assert_eq!(pause(BUSY, Some("2"), Duration::ZERO), two); + assert_eq!(pause(BUSY, Some(" 2 "), Duration::from_secs(8)), two); + // no pause asked for is still a second + assert_eq!( + pause(BUSY, Some("0"), Duration::ZERO), + Some(Duration::from_secs(1)) + ); + } + + #[test] + fn a_pause_past_the_window_is_not_waited_for() { + assert_eq!(pause(BUSY, Some("2"), Duration::from_millis(8_001)), None); + assert_eq!(pause(BUSY, Some("60"), Duration::ZERO), None); + } + + #[test] + fn only_a_busy_answer_is_asked_again() { + // an unloaded stage answers 503 without a retry time + assert_eq!(pause(BUSY, None, Duration::ZERO), None); + assert_eq!(pause(BUSY, Some("soon"), Duration::ZERO), None); + for status in [StatusCode::OK, StatusCode::CONFLICT, StatusCode::GONE] { + assert_eq!(pause(status, Some("2"), Duration::ZERO), None); + } + } +} diff --git a/crates/skippy-commands/src/receipts/recheck.rs b/crates/skippy-commands/src/receipts/recheck.rs new file mode 100644 index 00000000..48fe3ecd --- /dev/null +++ b/crates/skippy-commands/src/receipts/recheck.rs @@ -0,0 +1,67 @@ +//! `skippy recheck-receipt`: checks an audit's evidence again from the +//! evidence file and the claimed GGUF alone. A receipt that names its model +//! as `repo@revision/file` needs nothing else: the GGUF is read from Hugging +//! Face by range. +//! +//! The checks are those of [`skippy_receipt_audit::recheck`]. This module +//! reads the evidence file, opens the claimed model, and prints the report. + +use std::path::PathBuf; + +use anyhow::{Context, Result, bail}; +use skippy_receipt_audit::claimed_file::{self, HfFile}; +use skippy_receipt_audit::claimed_model::LoadClaimedModel; +use skippy_receipt_audit::output::NoAuditOutput; +use skippy_receipt_audit::recheck::recheck_evidence; +use skippy_receipt_audit::turn_audit::{TurnAudit, claimed_layer_count}; +use skippy_receipts::evidence::Evidence; + +pub struct RecheckReceiptCommand { + pub evidence: PathBuf, + /// The GGUF the receipt claims: a file here or `repo@revision/file` on + /// Hugging Face. Without it, the model the receipt names, when that is + /// a Hugging Face file. + pub claimed_model: Option, +} + +/// Prints the verdict the evidence's checks give, and ends with it: `Ok` +/// for a pass, else an error that carries the outcome's exit code +/// ([`super::exit_code`]). +pub fn recheck(command: RecheckReceiptCommand, load: LoadClaimedModel<'_>) -> Result<()> { + let audit = rechecked(&command, load) + .unwrap_or_else(|error| TurnAudit::NoAudit(NoAuditOutput::new("", format!("{error:#}")))); + super::conclude(audit, None) +} + +/// Opens the evidence and the claimed model. An error is this machine's: +/// the file or the GGUF cannot be read. +fn rechecked(command: &RecheckReceiptCommand, load: LoadClaimedModel<'_>) -> Result { + let text = std::fs::read(&command.evidence) + .with_context(|| format!("read evidence {}", command.evidence.display()))?; + let evidence: Evidence = serde_json::from_slice(&text).context("decode the evidence")?; + let cache_root = claimed_file::default_cache_root()?; + let claimed = match &command.claimed_model { + Some(path) => claimed_file::open(path, &cache_root)?, + // the node wrote this name: it is a Hugging Face file at a commit, + // and never a file here + None if HfFile::parse(&evidence.receipt.model).is_some() => { + claimed_file::open_named_by_receipt(&evidence.receipt.model, &cache_root)? + } + None => bail!( + "the receipt names its model as {:?}, not repo@revision/file on Hugging Face; pass --claimed-model", + evidence.receipt.model + ), + }; + let layer_count = claimed_layer_count(&claimed.path)?; + let model = load(claimed.path); + let mut audit = recheck_evidence(&evidence, &claimed.weights, model.as_ref(), layer_count); + if command.claimed_model.is_none() + && let TurnAudit::Audited { output, .. } = &mut audit + { + output.notes.push(COMMIT_FROM_RECEIPT.to_owned()); + } + Ok(audit) +} + +/// What a recheck says when the receipt alone named the claimed model. +const COMMIT_FROM_RECEIPT: &str = "the claimed model's commit was taken from the receipt, and was not checked against a branch: Hugging Face also serves the commits of pull requests, which anyone can open; pass --claimed-model repo@revision/file to name the model yourself"; diff --git a/crates/skippy-ffi/README.md b/crates/skippy-ffi/README.md index aca87ea2..1c94b367 100644 --- a/crates/skippy-ffi/README.md +++ b/crates/skippy-ffi/README.md @@ -105,7 +105,7 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.87`. The patch header in +The staged ABI is versioned as `0.1.88`. 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. diff --git a/crates/skippy-ffi/src/bindings/skippy.rs b/crates/skippy-ffi/src/bindings/skippy.rs index 644752c9..3e227a44 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 = 87; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 88; 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; @@ -22,6 +22,7 @@ pub const SKIPPY_MAX_DRY_SEQUENCE_BREAKER_BYTES: u32 = 16; pub const SKIPPY_SAMPLING_FLAG_ENABLED: u32 = 1; pub const SKIPPY_SAMPLING_FLAG_IGNORE_EOS: u32 = 2; pub const SKIPPY_SAMPLING_FLAG_LOGPROBS: u32 = 4; +pub const SKIPPY_SAMPLING_FLAG_INDEXED_DRAW: u32 = 8; pub const SKIPPY_GLM_DSA_POLICY_PROFILE_NONE: u32 = 0; pub const SKIPPY_GLM_DSA_POLICY_PROFILE_V1: u32 = 1; pub const SKIPPY_TRISTATE_AUTO: i32 = -1; @@ -1931,6 +1932,457 @@ unsafe extern "C" { ) -> skippy_status; } #[repr(u32)] +#[doc = " @brief A per-layer tensor reported by the recorder, a replay or a glue evaluation."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_receipt_tensor_kind { + #[doc = " Residual stream entering the layer; layer == layer_end is the stage output."] + Residual = 0, + #[doc = " A per-token value entering a token-mixing region."] + MixingInput = 1, + #[doc = " A row written to a KV cache, as stored and in the cache's type. A glue\n evaluation reports the f32 row before it is stored instead."] + MixingStored = 2, + #[doc = " A value leaving a token-mixing region."] + MixingOutput = 3, + #[doc = " Replay and glue evaluation: the input of a weight matmul."] + MatmulInput = 4, + #[doc = " Replay: the output of a weight matmul."] + MatmulOutput = 5, + #[doc = " Replay and glue evaluation: the expert of every slot of an expert matmul, I32."] + ExpertIds = 6, + #[doc = " Replay: the output of a selection (ARGSORT, TOP_K) made by glue, I32."] + Selection = 7, + #[doc = " Glue evaluation: the scores a selection ranks."] + SelectionScores = 8, + #[doc = " Replay of a final stage that replays its last layer: the logits of\n the ubatch's output rows, F32, with layer == layer_end."] + Logits = 9, + #[doc = " The state a recurrent token-mixing op reads before the ubatch, F32.\n Column s is the state of the ubatch's s-th sequence, whose tokens are\n the s-th run of n_tokens / n_cols tokens. A region evaluation takes\n one column: the state before its first position."] + MixingState = 10, + #[doc = " Region evaluation: the state the op writes back after the tokens,\n F32, with the index of the MIXING_STATE it replaces."] + MixingStateOut = 11, +} +#[repr(u32)] +#[doc = " @brief Flags of a reported tensor."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_receipt_tensor_flag { + #[doc = " MATMUL_*: the matmul's output reaches a selection before any other\n weight matmul, so an auditor checks all of its rows."] + Router = 1, +} +#[doc = " @brief One reported tensor, column per token."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_tensor { + pub layer: i32, + #[doc = " A skippy_receipt_tensor_kind."] + pub kind: i32, + #[doc = " Ordinal among the layer's tensors of this kind, in graph order.\n MATMUL_INPUT, MATMUL_OUTPUT and EXPERT_IDS share their matmul's\n ordinal; SELECTION and SELECTION_SCORES share their selection's."] + pub index: i32, + #[doc = " ggml type of the values: F32, I32, or the cache type of a stored row."] + pub ggml_type: i32, + #[doc = " skippy_receipt_tensor_flag bits."] + pub flags: i32, + #[doc = " Elements per column."] + pub len: i64, + #[doc = " Bytes per column."] + pub row_bytes: i64, + #[doc = " Number of columns: the ubatch's token count, or its output-row count when\n the layer keeps only output rows (the last layer of a final stage)."] + pub n_cols: i64, + #[doc = " Column j at `values + j * row_bytes`, or NULL when `digests` is set."] + pub values: *const ::std::os::raw::c_void, + #[doc = " MATMUL_* and EXPERT_IDS: the weight's tensor name. Otherwise the graph node's name, for diagnostics."] + pub name: *const ::std::os::raw::c_char, + #[doc = " While serving on a device that can hash: per column, the 32-byte BLAKE3\n hash of its `row_bytes` bytes, computed on the device so the values\n never reach the host. `values` is NULL then. NULL otherwise."] + pub digests: *const u8, +} +#[repr(u32)] +#[doc = " @brief Which positions an attention op's queries read."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_receipt_attention_window_kind { + #[doc = " Every earlier position, and its own."] + Causal = 0, + #[doc = " The last `window` positions up to its own."] + Sliding = 1, + #[doc = " Earlier positions in its own chunk of `window` positions."] + Chunked = 2, +} +#[doc = " @brief One attention op of a reported layer.\n\n Says which of the layer's committed values the op reads and writes, and\n how it combines them: `output = softmax(scale * q k^T, softcapped, over\n the window) v` per query head, with K and V heads shared by\n `n_head / n_head_kv` query heads. Values are head-major: head h of a\n column is its elements `h * head_dim` to `(h + 1) * head_dim`."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_attention { + pub layer: i32, + #[doc = " Non-NULL when the attention check cannot follow the op: the reason. Nothing else is set."] + pub error: *const ::std::os::raw::c_char, + #[doc = " Indices of q among the MIXING_INPUT values, K and V among the MIXING_STORED rows, and the output among the MIXING_OUTPUT values."] + pub q_input: i32, + pub k_store: i32, + pub v_store: i32, + pub output: i32, + pub n_head: i32, + pub n_head_kv: i32, + pub head_dim_k: i32, + pub head_dim_v: i32, + #[doc = " Multiplies q k."] + pub scale: f32, + #[doc = " Nonzero: a logit x becomes `softcap * tanh(x / softcap)`."] + pub softcap: f32, + #[doc = " A skippy_receipt_attention_window_kind, and its size."] + pub window_kind: i32, + pub window: i32, + #[doc = " Per query head, a logit that only adds to the softmax's denominator, or NULL."] + pub sinks: *const f32, + #[doc = " Index among the MIXING_INPUT values of a gate that multiplies the\n output, value by value, before it leaves the token-mixing region; or -1.\n `output` is then the gated value."] + pub output_gate: i32, + #[doc = " Nonzero: before the gate, each head of the output is rotated in chunks\n of this many values, value i of a chunk becoming\n `sum_k output_rotation[i * output_rotation_n + k] * value k` (llama.cpp\n rotates V before a quantized KV cache stores it)."] + pub output_rotation_n: i32, + pub output_rotation: *const f32, + #[doc = " A ggml type the kernel rounds each head of q to before its dot with K,\n or -1: GGML_TYPE_Q8_0 (8-bit blocks of 32 values) for a quantized K\n cache, as the CPU and CUDA kernels do."] + pub q_rounding: i32, +} +#[doc = " @brief One computed ubatch.\n\n The tensor values and stage input rows of a ubatch reported by the\n recorder stay valid until the callback for the next ubatch returns, or the\n recorder is removed or replaced, so a caller can hash them while the next\n ubatch computes. Every other pointer is valid only during the callback."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_ubatch { + #[doc = " Replay step index, or -1 while serving."] + pub step: i64, + pub n_tokens: i32, + #[doc = " Per column: token id, sequence, position, output flag, and KV cell."] + pub token: *const i32, + pub seq: *const i32, + pub pos: *const i32, + pub output: *const i8, + pub cell: *const u32, + #[doc = " KV cells the attention graph covered."] + pub n_kv: u32, + #[doc = " Stage input rows (a stage after the first), or NULL. Row j at `input + j * input_row_bytes`."] + pub input: *const ::std::os::raw::c_void, + pub input_row_bytes: i64, + #[doc = " ggml type of the input rows."] + pub input_type: i32, + pub n_tensors: usize, + pub tensors: *const skippy_receipt_tensor, + #[doc = " Non-NULL when the ubatch cannot be receipted: the reason. Nothing else is set."] + pub error: *const ::std::os::raw::c_char, + #[doc = " Glue evaluation: weights read inside token-mixing regions, which nothing checks."] + pub n_unchecked_weights: usize, + pub unchecked_weights: *const *const ::std::os::raw::c_char, + #[doc = " Replay and glue evaluation: the attention ops of the reported layers."] + pub n_attention: usize, + pub attention: *const skippy_receipt_attention, +} +#[repr(u32)] +#[doc = " @brief KV-cache operations that the recorder reports."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_receipt_memory_op { + #[doc = " Every sequence lost all its cells."] + Clear = 0, + #[doc = " Cells of `seq` (every sequence if -1) in positions [p0, p1) were removed; p1 < 0 means no end."] + SeqRm = 1, + #[doc = " Cells of `seq` in [p0, p1) were shared with `seq_dst`."] + SeqCp = 2, + #[doc = " Every sequence except `seq` lost its cells."] + SeqKeep = 3, + #[doc = " Positions of `seq` in [p0, p1) were shifted or divided."] + SeqShift = 4, + #[doc = " Cells of `seq` (every sequence if -1) were loaded from saved state or\n from an imported KV page. Reported before the rows are written. The\n cells they go to are not reported, and may be freed cells that an\n earlier turn still reads, so any cell may hold other rows afterwards."] + StateRead = 5, + #[doc = " Cells moved to close gaps."] + Compact = 6, +} +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_memory_event { + #[doc = " A skippy_receipt_memory_op."] + pub op: i32, + pub seq: i32, + pub seq_dst: i32, + pub p0: i32, + pub p1: i32, +} +pub type skippy_receipt_ubatch_fn = ::std::option::Option< + unsafe extern "C" fn( + user_data: *mut ::std::os::raw::c_void, + ubatch: *const skippy_receipt_ubatch, + ), +>; +pub type skippy_receipt_memory_fn = ::std::option::Option< + unsafe extern "C" fn( + user_data: *mut ::std::os::raw::c_void, + event: *const skippy_receipt_memory_event, + ), +>; +unsafe extern "C" { + #[doc = " @brief Installs or, with both callbacks NULL, removes the receipt recorder.\n\n The memory callback runs on the thread that changes the KV cache. On a\n device that copies asynchronously, a ubatch's values reach the host while\n later ubatches compute, and the ubatch is reported late: on the decoding\n thread two ubatches later, before the next memory event, or on the thread\n that calls skippy_model_flush_receipt_recorder(). Otherwise each ubatch is\n reported on the decoding thread as soon as it is computed. Reports always\n arrive in the order the ubatches and memory events happened. The recorder\n marks the committed tensors as graph outputs, which keeps them\n alive and may disable some kernel fusions; replay marks the same tensors.\n The stage needs a plain KV cache, unified or with a stream per sequence\n (skippy_model_receipt_kv_streams()), and flash attention, so V rows are\n stored untransposed.\n\n The caller keeps the stage context idle during the call: nothing decodes\n on it, changes its KV cache, or flushes the recorder, on any thread. The\n decoding thread reads the recorder and the memory callback without a\n lock, so installing, replacing or removing them under it is a data race.\n `user_data` must stay valid until the call that removes or replaces the\n recorder returns.\n\n A context with a receipt capture (the stage context once a recorder is\n installed, and the contexts that replay and evaluate receipts) uses the\n dense-mask attention of a unified KV cache: the attention mask hides the\n cells of other sequences, and the attention op is not given each\n sequence's rows (ggml_flash_attn_ext_rows). The layer classifier, the\n replay and the attention opening do not read those row lists. Both ways\n attend to the same cells; a stage that serves several sequences from a\n unified cache loses the speedup of the row lists. The stage context keeps\n the dense mask after the recorder is removed."] + pub fn skippy_model_set_receipt_recorder( + model: *mut skippy_model, + on_ubatch: skippy_receipt_ubatch_fn, + on_memory: skippy_receipt_memory_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Reports the ubatches the recorder still holds back, if any.\n\n Call it before reading what the recorder reported, for example to commit\n a turn: the last ubatches of a turn are otherwise reported only with later\n ubatches or the next memory event. It waits for their values to reach the\n host. Safe to call from any thread, and when no recorder is installed."] + pub fn skippy_model_flush_receipt_recorder( + model: *mut skippy_model, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +#[repr(u32)] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_receipt_replay_kind { + #[doc = " Decode one recorded ubatch."] + Decode = 0, + #[doc = " Remove positions [p0, p1) of the replayed sequence (p1 < 0: no end)."] + SeqRm = 1, +} +#[doc = " @brief One replay step. A decode step has the fields of a recorded ubatch."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_replay_step { + #[doc = " A skippy_receipt_replay_kind."] + pub kind: i32, + pub n_tokens: i32, + pub token: *const i32, + pub seq: *const i32, + pub pos: *const i32, + pub output: *const i8, + pub cell: *const u32, + pub n_kv: u32, + pub input: *const ::std::os::raw::c_void, + pub input_row_bytes: i64, + pub input_type: i32, + #[doc = " SEQ_RM range."] + pub p0: i32, + pub p1: i32, + #[doc = " Nonzero to report this step's tensors through the capture callback."] + pub capture: i32, +} +unsafe extern "C" { + #[doc = " @brief Replays one sequence in the model's scratch context.\n\n The scratch context is created on first use with the stage context's\n parameters and room for the KV cells the steps use, not the stage's whole\n context. It is kept until skippy_model_release_receipt_scratch(), and a\n later replay that needs more cells creates it again. A replay of the\n sequence skippy_model_seed_receipt_replay() seeded last starts from the\n seeded cells, which must cover the cells its steps use; any other starts\n from an empty cache. After every decode step, the columns of sequences\n other than `seq` are removed. A captured step reports, for each\n of the `n_layers` sorted `layers`, the layer's committed tensors, its\n weight matmuls' inputs, outputs and experts, its selections, and the\n residual leaving it. Every step stops computing once those are done, so\n later layers and the output head are skipped and their values are\n undefined.\n\n `seq` and the sequences of every step must be sequences of the stage\n context, a step's `n_kv` must fit the replay cache, and a step's input\n rows must have the type and size of the stage's imported activation. The\n call fails with SKIPPY_STATUS_INVALID_ARGUMENT, before any step runs, when\n a step breaks one of these."] + pub fn skippy_model_replay_receipt( + model: *mut skippy_model, + seq: i32, + layers: *const i32, + n_layers: usize, + steps: *const skippy_receipt_replay_step, + n_steps: usize, + on_capture: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Replays like skippy_model_replay_receipt(), reporting only the committed tensors.\n\n A captured step reports, for each of the `layers`, the tensors the\n recorder commits (the residual entering it, its token-mixing values and\n the residual leaving it) and a final stage's logits, and no matmul or\n selection. The recorder marks the same tensors, so a backend fuses the\n layer's ops as it did when serving, and the committed values are\n reproduced bit for bit even where the extra tensors of a full replay\n keep a backend from fusing them."] + pub fn skippy_model_replay_receipt_committed( + model: *mut skippy_model, + seq: i32, + layers: *const i32, + n_layers: usize, + steps: *const skippy_receipt_replay_step, + n_steps: usize, + on_capture: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +#[doc = " @brief A committed value an anchored replay writes into one token's column."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_anchor { + #[doc = " The decode step, as an index into the replay's steps."] + pub step: usize, + #[doc = " The token: its sequence and position in that step."] + pub seq: i32, + pub pos: i32, + pub layer: i32, + #[doc = " RESIDUAL, the residual entering `layer`, or MIXING_OUTPUT."] + pub kind: i32, + pub index: i32, + #[doc = " f32 elements of the column."] + pub len: i64, + pub values: *const f32, +} +unsafe extern "C" { + #[doc = " @brief Replays like skippy_model_replay_receipt(), from committed values at anchored tokens.\n\n As soon as a step computes the residual entering an anchored layer, or one\n of its token-mixing outputs, the anchor's values replace the token's\n column, before anything reads it. The matmuls and selections the replay\n reports for the anchored tokens then follow from the committed values,\n even where this replay computes the layers before them, or the context\n the token-mixing ops read, differently from the turn: a backend fuses\n fewer ops when more tensors are reported. Every anchor's layer must be\n one of `layers`, and its step a decode step."] + pub fn skippy_model_replay_receipt_anchored( + model: *mut skippy_model, + seq: i32, + layers: *const i32, + n_layers: usize, + steps: *const skippy_receipt_replay_step, + n_steps: usize, + anchors: *const skippy_receipt_anchor, + n_anchors: usize, + on_capture: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Seeds the next receipt replay of `seq` with cells of the stage context.\n\n Copies the K and V rows of `cells` from the stage context's KV cache into\n the same cells of the scratch context, which is made to hold `n_cells`\n cells, and marks them there as positions `pos` of `seq`. A turn that\n continued a sequence, or started from a cached prefix, then replays only\n its own ubatches on top of the prefix it attended to. Fails, seeding\n nothing, unless every cell holds position `pos[i]` in the stage context,\n or no sequence holds it any more; the sequences sharing it there do not\n matter. A freed cell keeps its rows until a ubatch writes it, which the\n recorder reports, so the caller checks its rows from what it recorded.\n Models with more than one position per token cannot seed a freed cell.\n The caller keeps the stage context idle during the call. The seed lasts\n until the next replay or seeding."] + pub fn skippy_model_seed_receipt_replay( + model: *mut skippy_model, + seq: i32, + cells: *const u32, + pos: *const i32, + n_seeded: usize, + n_cells: u32, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Reads the rows the stage context stored in some KV cells for one layer.\n\n Calls `on_rows` once with a ubatch of `n_cells` columns, cell j holding\n `cells[j]` of the stream of `seq`, whose tensors are the MIXING_STORED\n rows of `layer`, by index, read from the stage context's cache exactly as\n the recorder commits them. The recorder must be installed and the stage\n context must have computed a ubatch since, so its graph names the layer's\n cache rows. The caller keeps the stage context idle during the call."] + pub fn skippy_model_read_receipt_rows( + model: *mut skippy_model, + layer: i32, + seq: i32, + cells: *const u32, + n_cells: usize, + on_rows: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Pins the KV cells a recent turn's opening may still read.\n\n Replaces the pinned cells of the stage context with `cells`, cell i in\n stream `streams[i]`; none when `n_cells` is 0. While a pinned cell is\n empty, which it is once its sequences free it, the stage context places\n ubatches in other cells, and uses it only when a ubatch fits nowhere else.\n A pin costs no memory: it keeps the rows of a finished turn readable for\n its challenge window while the cache has room. Safe while the stage context computes: a\n ubatch is placed with the cells pinned before it or after it."] + pub fn skippy_model_pin_receipt_cells( + model: *mut skippy_model, + streams: *const u32, + cells: *const u32, + n_cells: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +#[doc = " @brief Receives a sequence's recurrent state before a turn of it.\n\n `bytes` holds the recurrent state of `seq` in the stage context before the\n first ubatch of the turn computes, as the context's recurrent memory\n serializes it: the recurrent part of a sequence state alone, without the\n header and the KV cells that llama_state_seq_get_data_ext() writes around\n it, so only skippy_model_seed_receipt_state() reads it. It is null, with\n `n_bytes` 0, when the state could not be exported. Valid for the call\n only."] +pub type skippy_receipt_state_fn = ::std::option::Option< + unsafe extern "C" fn( + user_data: *mut ::std::os::raw::c_void, + seq: i32, + bytes: *const ::std::os::raw::c_void, + n_bytes: usize, + ), +>; +unsafe extern "C" { + #[doc = " @brief Reports the recurrent state each turn of a sequence starts from.\n\n A replay cannot recompute a recurrent layer's state from the turn's own\n ubatches, so for a hybrid model, whose attention layers use a plain KV\n cache and whose other layers keep recurrent state (the gated delta net,\n Mamba), the recorder installed by skippy_model_set_receipt_recorder()\n calls `on_state` on the decoding thread before the first ubatch of each\n turn, after it reports the ubatches before it. `bytes` is null when the\n state cannot be read, and is valid only during the call. A turn starts\n at a sequence's first ubatch, after the sequence is removed whole, and\n after skippy_model_arm_receipt_state().\n Sets `*out_recurrent` to whether the model has hybrid memory; without\n it `on_state` is never called. A null `on_state` stops the reports."] + pub fn skippy_model_set_receipt_state_observer( + model: *mut skippy_model, + on_state: skippy_receipt_state_fn, + user_data: *mut ::std::os::raw::c_void, + out_recurrent: *mut bool, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Starts a new turn of `seq` for the receipt state observer.\n\n Its next ubatch reports the sequence's recurrent state first. Safe while\n the stage context computes."] + pub fn skippy_model_arm_receipt_state( + model: *mut skippy_model, + seq: i32, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Seeds the next receipt replay of `seq` with recurrent state.\n\n Imports `bytes`, a state the observer reported, into `seq` of the\n scratch context, after skippy_model_seed_receipt_replay() seeded its KV\n cells (possibly none). The replay then starts its first ubatch from the\n state the turn started from. The seed lasts until the next replay or\n seeding."] + pub fn skippy_model_seed_receipt_state( + model: *mut skippy_model, + seq: i32, + bytes: *const ::std::os::raw::c_void, + n_bytes: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Reports how the stage context's KV cache lays out its cells.\n\n Writes the number of streams: 1 for a unified cache, which every\n sequence shares, or one per sequence, stream s holding the cells of\n sequence s. The cells the recorder reports, a replay places, a seed\n copies and a pin holds are indices in the stream of their sequence. A\n `seq_cp` between sequences of different streams copies the source's\n whole stream into the destination's."] + pub fn skippy_model_receipt_kv_streams( + model: *mut skippy_model, + out_streams: *mut u32, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Frees the scratch context that receipt replays run in.\n\n The next replay creates it again. When a replay is running, the context\n is kept and the call still succeeds."] + pub fn skippy_model_release_receipt_scratch( + model: *mut skippy_model, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +#[doc = " @brief A value a glue evaluation uses instead of computing it."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_glue_value { + #[doc = " MATMUL_OUTPUT, MIXING_OUTPUT or SELECTION."] + pub kind: i32, + pub index: i32, + #[doc = " F32, or I32 for SELECTION."] + pub ggml_type: i32, + #[doc = " Elements per column. Column j at `values + j * len` elements."] + pub len: i64, + pub values: *const ::std::os::raw::c_void, +} +#[doc = " @brief Opened values of one layer at a few positions."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_receipt_glue_request { + pub layer: i32, + pub n_cols: i32, + #[doc = " Per column: the position."] + pub pos: *const i32, + #[doc = " Residual stream entering the layer. Column j at `residual + j * residual_len`."] + pub residual: *const f32, + pub residual_len: i64, + #[doc = " One value for every weight matmul output, token-mixing output and selection of the layer."] + pub n_values: usize, + pub values: *const skippy_receipt_glue_value, +} +unsafe extern "C" { + #[doc = " @brief Evaluates the glue of one layer on opened values.\n\n The model must hold `layer`; an auditor loads a stage of that layer alone.\n Each column is computed as its own sequence at its position, starting\n from the opened residual. Every weight matmul, token-mixing output and\n selection takes the given value instead of being computed, so the\n layer's large weights are never read. `on_result` is called once with the\n computed values: weight matmul inputs and experts, token-mixing inputs,\n KV rows before storage, selection scores, the residual leaving the layer,\n and the weights read inside token-mixing regions.\n\n The opened values come from the node being audited, so none is trusted.\n The call fails with SKIPPY_STATUS_INVALID_ARGUMENT when the request has\n more columns than a context has sequences, a negative position, a\n residual of another width than the layer reads, or a value of a kind,\n type or length the evaluation does not take. A value that does not fit\n the node it replaces, or a SELECTION id that is no row of what the\n selection chooses from, is reported through `on_result` as an error."] + pub fn skippy_model_eval_receipt_glue( + model: *mut skippy_model, + request: *const skippy_receipt_glue_request, + on_result: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Evaluates the recurrent token mixing of one layer on opened values.\n\n The model must hold `layer`, as for skippy_model_eval_receipt_glue(). The\n columns are consecutive positions of one sequence, computed in one\n ubatch. Every MIXING_INPUT of the layer takes the given value, each\n MIXING_STATE the given state (one column), and the weight matmuls compute\n nothing; the token mixing reads no residual, so it may be zeros.\n `on_result` is called once with the MIXING_OUTPUT values the\n token-mixing ops compute from them and the MIXING_STATE_OUT states they\n leave. A layer whose token mixing reads a KV cache, or keeps no\n recurrent state, is refused. The request is checked as for\n skippy_model_eval_receipt_glue(); a region holds at most a context of\n positions."] + pub fn skippy_model_eval_receipt_region( + model: *mut skippy_model, + request: *const skippy_receipt_glue_request, + on_result: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Computes the residual entering layer 0 for tokens at positions.\n\n The model must hold layer 0. Each of the `n_cols` columns is its own\n sequence of one token. `on_result` is called once with the RESIDUAL\n tensor of layer 0, a column per token, as the stage computes it from the\n token embedding. A token outside the vocabulary, a negative position or\n more columns than a context has sequences fails the call with\n SKIPPY_STATUS_INVALID_ARGUMENT."] + pub fn skippy_model_eval_receipt_entry( + model: *mut skippy_model, + tokens: *const i32, + pos: *const i32, + n_cols: i32, + on_result: skippy_receipt_ubatch_fn, + user_data: *mut ::std::os::raw::c_void, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Compares a stored KV row with the f32 row an auditor computed.\n\n Sets `stored_error` to the L2 distance between the dequantized stored row\n and `computed`, `rounding_error` to the distance between `computed` and\n its own round trip through `ggml_type`, and `norm` to the L2 norm of\n `computed`. An honestly stored row is about one rounding error away.\n `stored` holds `stored_len` bytes, which must be the size of a row of `n`\n values of `ggml_type`: the type and the bytes come from the opening, so a\n row of any other size is refused, not read."] + pub fn skippy_receipt_stored_row_error( + ggml_type: i32, + stored: *const ::std::os::raw::c_void, + stored_len: usize, + computed: *const f32, + n: i64, + stored_error: *mut f64, + rounding_error: *mut f64, + norm: *mut f64, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Names the source the runtime was built from.\n\n `llama.cpp patches `, as the\n prepared llama.cpp checkout recorded them when the library was built, or\n `unknown` for a checkout without that record. A receipt names it, so an\n auditor knows whether its own runtime computes like the node's."] + pub fn skippy_receipt_runtime_source() -> *const ::std::os::raw::c_char; +} +#[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum skippy_workload_kind { CausalGeneration = 0, diff --git a/crates/skippy-ffi/src/dynamic.rs b/crates/skippy-ffi/src/dynamic.rs index 4653ddc6..cd9ec2f7 100644 --- a/crates/skippy-ffi/src/dynamic.rs +++ b/crates/skippy-ffi/src/dynamic.rs @@ -15,8 +15,9 @@ use crate::{ MtmdBitmap, MtmdContext, MtmdContextParams, MtmdDecoderPos, MtmdGenAudioInfo, MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, MtmdHelperGenAudio, MtmdHelperGenAudioInput, MtmdHelperInitOpt, MtmdHelperVideo, MtmdInputChunkType, MtmdInputChunks, MtmdInputText, - NativeMtpDraft, NativeRuntimeLoadError, NgramCache, Opaque, RuntimeConfig, SamplingConfig, - Session, SkippyDecodeStepSampledMtpFn, SkippyModelAttachMtpDraftModelFn, + NativeMtpDraft, NativeRuntimeLoadError, NgramCache, Opaque, ReceiptAnchor, ReceiptGlueRequest, + ReceiptMemoryFn, ReceiptReplayStep, ReceiptStateFn, ReceiptUbatchFn, RuntimeConfig, + SamplingConfig, Session, SkippyDecodeStepSampledMtpFn, SkippyModelAttachMtpDraftModelFn, SkippyRuntimeEventReporterV1, StagePlan, StagePlanDescV1, StagePlanProfileDescV1, StagePlanStateDescV1, StagePlanStringRefV1, StagePlanValueDescV1, StagePlanValueKind, StagePlanner, StagePlannerConfigV1, Status, SystemOneSlot, TensorInfo, TokenLogprobs, @@ -252,6 +253,24 @@ dynamic_symbols! { skippy_session_copy_output_activation_frame(session: *mut Session, token_count: usize, output_desc: *mut ActivationDesc, output_payload: *mut c_void, output_payload_capacity: usize, out_output_payload_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_session_last_token_signal(session: *mut Session, out_signal: *mut TokenSignal, out_error: *mut *mut Error) -> Status; skippy_session_take_token_logprobs(session: *mut Session, out_entries: *mut TokenLogprobs, capacity: usize, out_count: *mut usize, out_error: *mut *mut Error) -> Status; + skippy_model_set_receipt_recorder(model: *mut Model, on_ubatch: ReceiptUbatchFn, on_memory: ReceiptMemoryFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_release_receipt_scratch(model: *mut Model, out_error: *mut *mut Error) -> Status; + skippy_model_flush_receipt_recorder(model: *mut Model, out_error: *mut *mut Error) -> Status; + skippy_model_eval_receipt_glue(model: *mut Model, request: *const ReceiptGlueRequest, on_result: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_eval_receipt_region(model: *mut Model, request: *const ReceiptGlueRequest, on_result: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_eval_receipt_entry(model: *mut Model, tokens: *const i32, pos: *const i32, n_cols: i32, on_result: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_receipt_runtime_source() -> *const c_char; + skippy_receipt_stored_row_error(ggml_type: i32, stored: *const c_void, stored_len: usize, computed: *const f32, n: i64, stored_error: *mut f64, rounding_error: *mut f64, norm: *mut f64, out_error: *mut *mut Error) -> Status; + skippy_model_replay_receipt(model: *mut Model, seq: i32, layers: *const i32, n_layers: usize, steps: *const ReceiptReplayStep, n_steps: usize, on_capture: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_replay_receipt_committed(model: *mut Model, seq: i32, layers: *const i32, n_layers: usize, steps: *const ReceiptReplayStep, n_steps: usize, on_capture: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_replay_receipt_anchored(model: *mut Model, seq: i32, layers: *const i32, n_layers: usize, steps: *const ReceiptReplayStep, n_steps: usize, anchors: *const ReceiptAnchor, n_anchors: usize, on_capture: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_seed_receipt_replay(model: *mut Model, seq: i32, cells: *const u32, pos: *const i32, n_seeded: usize, n_cells: u32, out_error: *mut *mut Error) -> Status; + skippy_model_read_receipt_rows(model: *mut Model, layer: i32, seq: i32, cells: *const u32, n_cells: usize, on_rows: ReceiptUbatchFn, user_data: *mut c_void, out_error: *mut *mut Error) -> Status; + skippy_model_pin_receipt_cells(model: *mut Model, streams: *const u32, cells: *const u32, n_cells: usize, out_error: *mut *mut Error) -> Status; + skippy_model_receipt_kv_streams(model: *mut Model, out_streams: *mut u32, out_error: *mut *mut Error) -> Status; + skippy_model_set_receipt_state_observer(model: *mut Model, on_state: ReceiptStateFn, user_data: *mut c_void, out_recurrent: *mut bool, out_error: *mut *mut Error) -> Status; + skippy_model_arm_receipt_state(model: *mut Model, seq: i32, out_error: *mut *mut Error) -> Status; + skippy_model_seed_receipt_state(model: *mut Model, seq: i32, bytes: *const c_void, n_bytes: usize, out_error: *mut *mut Error) -> Status; skippy_session_signal_window(session: *mut Session, window_tokens: u32, out_window: *mut GenerationSignalWindow, out_error: *mut *mut Error) -> Status; skippy_trim_session(session: *mut Session, token_count: u64, out_error: *mut *mut Error) -> Status; skippy_retire_verify_checkpoint(session: *mut Session, token_start: u64, token_count: u64, out_error: *mut *mut Error) -> Status; diff --git a/crates/skippy-ffi/src/lib.rs b/crates/skippy-ffi/src/lib.rs index 0adb5118..aa191f7f 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 = 87; +pub const ABI_VERSION_PATCH: u32 = 88; // 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 @@ -31,6 +31,7 @@ mod dynamic; pub mod llama_draft; mod model; mod multimodal; +mod receipts; mod runtime; mod sampling; mod stage_plan; @@ -117,6 +118,7 @@ pub use multimodal::{ MtmdHelperGenAudioOutputMode, MtmdHelperGenAudioOutputType, MtmdHelperInitOpt, MtmdHelperVideo, MtmdHelperVideoInitParams, MtmdInputChunkType, MtmdInputChunks, MtmdInputText, }; +pub use receipts::*; pub use runtime::{ NativeRuntimeLoadError, abi_features, llama_model_is_diffusion, llama_model_is_hybrid, llama_model_is_recurrent, llama_model_meta_val_str, try_abi_features, @@ -124,7 +126,8 @@ pub use runtime::{ pub use sampling::{ GenerationSignalWindow, LogprobEntry, MAX_DRY_SEQUENCE_BREAKER_BYTES, MAX_DRY_SEQUENCE_BREAKERS, MAX_SAMPLERS, MAX_TOP_LOGPROBS, NATIVE_MTP_MAX_DRAFT_TOKENS, - NativeMtpDraft, SAMPLING_FLAG_LOGPROBS, SamplingConfig, TokenLogprobs, TokenSignal, + NativeMtpDraft, SAMPLING_FLAG_INDEXED_DRAW, SAMPLING_FLAG_LOGPROBS, SamplingConfig, + TokenLogprobs, TokenSignal, }; pub use stage_plan::{ STAGE_PLAN_DESC_V1_ABI_VERSION, STAGE_PLAN_MAX_DIMS, STAGE_PLAN_PROFILE_DESC_V1_ABI_VERSION, @@ -187,17 +190,26 @@ pub use dynamic::{ 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_laya_read, skippy_laya_tokenize, skippy_model_arm_receipt_state, + skippy_model_attach_mtp_draft_model_fn, skippy_model_eval_receipt_entry, + skippy_model_eval_receipt_glue, skippy_model_eval_receipt_region, + skippy_model_flush_receipt_recorder, 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_pin_receipt_cells, + skippy_model_read_receipt_rows, skippy_model_receipt_kv_streams, + skippy_model_release_receipt_scratch, skippy_model_replay_receipt, + skippy_model_replay_receipt_anchored, skippy_model_replay_receipt_committed, + skippy_model_seed_receipt_replay, skippy_model_seed_receipt_state, + skippy_model_set_receipt_recorder, skippy_model_set_receipt_state_observer, 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_receipt_runtime_source, skippy_receipt_stored_row_error, 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, @@ -259,24 +271,32 @@ pub use static_bindings::{ 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, skippy_model_free, skippy_model_info_free, + skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, skippy_model_arm_receipt_state, + skippy_model_attach_mtp_draft_model, skippy_model_eval_receipt_entry, + skippy_model_eval_receipt_glue, skippy_model_eval_receipt_region, + skippy_model_flush_receipt_recorder, 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_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_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_model_output_activation_boundary, skippy_model_pin_receipt_cells, + skippy_model_read_receipt_rows, skippy_model_receipt_kv_streams, + skippy_model_release_receipt_scratch, skippy_model_replay_receipt, + skippy_model_replay_receipt_anchored, skippy_model_replay_receipt_committed, + skippy_model_seed_receipt_replay, skippy_model_seed_receipt_state, + skippy_model_set_receipt_recorder, skippy_model_set_receipt_state_observer, + 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_receipt_runtime_source, skippy_receipt_stored_row_error, + 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_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, diff --git a/crates/skippy-ffi/src/receipts.rs b/crates/skippy-ffi/src/receipts.rs new file mode 100644 index 00000000..4983e040 --- /dev/null +++ b/crates/skippy-ffi/src/receipts.rs @@ -0,0 +1,50 @@ +//! Ergonomic aliases for the generated receipt ABI types. + +use crate::bindings::skippy as ffi; +use ffi::{ + skippy_receipt_attention_window_kind as AttentionWindow, skippy_receipt_memory_op as MemoryOp, + skippy_receipt_replay_kind as ReplayKind, skippy_receipt_tensor_flag as TensorFlag, + skippy_receipt_tensor_kind as TensorKind, +}; + +pub const RECEIPT_TENSOR_RESIDUAL: i32 = TensorKind::Residual as i32; +pub const RECEIPT_TENSOR_MIXING_INPUT: i32 = TensorKind::MixingInput as i32; +pub const RECEIPT_TENSOR_MIXING_STORED: i32 = TensorKind::MixingStored as i32; +pub const RECEIPT_TENSOR_MIXING_OUTPUT: i32 = TensorKind::MixingOutput as i32; +pub const RECEIPT_TENSOR_MATMUL_INPUT: i32 = TensorKind::MatmulInput as i32; +pub const RECEIPT_TENSOR_MATMUL_OUTPUT: i32 = TensorKind::MatmulOutput as i32; +pub const RECEIPT_TENSOR_EXPERT_IDS: i32 = TensorKind::ExpertIds as i32; +pub const RECEIPT_TENSOR_SELECTION: i32 = TensorKind::Selection as i32; +pub const RECEIPT_TENSOR_SELECTION_SCORES: i32 = TensorKind::SelectionScores as i32; +pub const RECEIPT_TENSOR_LOGITS: i32 = TensorKind::Logits as i32; +pub const RECEIPT_TENSOR_MIXING_STATE: i32 = TensorKind::MixingState as i32; +pub const RECEIPT_TENSOR_MIXING_STATE_OUT: i32 = TensorKind::MixingStateOut as i32; + +pub const RECEIPT_TENSOR_ROUTER: i32 = TensorFlag::Router as i32; + +pub const RECEIPT_MEMORY_CLEAR: i32 = MemoryOp::Clear as i32; +pub const RECEIPT_MEMORY_SEQ_RM: i32 = MemoryOp::SeqRm as i32; +pub const RECEIPT_MEMORY_SEQ_CP: i32 = MemoryOp::SeqCp as i32; +pub const RECEIPT_MEMORY_SEQ_KEEP: i32 = MemoryOp::SeqKeep as i32; +pub const RECEIPT_MEMORY_SEQ_SHIFT: i32 = MemoryOp::SeqShift as i32; +pub const RECEIPT_MEMORY_STATE_READ: i32 = MemoryOp::StateRead as i32; +pub const RECEIPT_MEMORY_COMPACT: i32 = MemoryOp::Compact as i32; + +pub const RECEIPT_REPLAY_DECODE: i32 = ReplayKind::Decode as i32; +pub const RECEIPT_REPLAY_SEQ_RM: i32 = ReplayKind::SeqRm as i32; + +pub const RECEIPT_ATTENTION_CAUSAL: i32 = AttentionWindow::Causal as i32; +pub const RECEIPT_ATTENTION_SLIDING: i32 = AttentionWindow::Sliding as i32; +pub const RECEIPT_ATTENTION_CHUNKED: i32 = AttentionWindow::Chunked as i32; + +pub type ReceiptTensor = ffi::skippy_receipt_tensor; +pub type ReceiptUbatch = ffi::skippy_receipt_ubatch; +pub type ReceiptMemoryEvent = ffi::skippy_receipt_memory_event; +pub type ReceiptReplayStep = ffi::skippy_receipt_replay_step; +pub type ReceiptAnchor = ffi::skippy_receipt_anchor; +pub type ReceiptAttention = ffi::skippy_receipt_attention; +pub type ReceiptGlueValue = ffi::skippy_receipt_glue_value; +pub type ReceiptGlueRequest = ffi::skippy_receipt_glue_request; +pub type ReceiptUbatchFn = ffi::skippy_receipt_ubatch_fn; +pub type ReceiptMemoryFn = ffi::skippy_receipt_memory_fn; +pub type ReceiptStateFn = ffi::skippy_receipt_state_fn; diff --git a/crates/skippy-ffi/src/sampling.rs b/crates/skippy-ffi/src/sampling.rs index 1c47ca6e..9e1ad42d 100644 --- a/crates/skippy-ffi/src/sampling.rs +++ b/crates/skippy-ffi/src/sampling.rs @@ -13,6 +13,10 @@ pub type SamplingConfig = bindings::skippy::skippy_sampling_config; /// Record each sampled token's log-probability and top alternatives. pub const SAMPLING_FLAG_LOGPROBS: u32 = bindings::skippy::SKIPPY_SAMPLING_FLAG_LOGPROBS; +/// Draw each sampled token with a uniform derived from the seed and the +/// token's position, so a receipt's client can replay the draw. +pub const SAMPLING_FLAG_INDEXED_DRAW: u32 = bindings::skippy::SKIPPY_SAMPLING_FLAG_INDEXED_DRAW; + /// Alternatives recorded per token with [`SAMPLING_FLAG_LOGPROBS`]. pub const MAX_TOP_LOGPROBS: usize = bindings::skippy::SKIPPY_MAX_TOP_LOGPROBS as usize; diff --git a/crates/skippy-inference-api/Cargo.toml b/crates/skippy-inference-api/Cargo.toml index 44d3db13..0e540cdf 100644 --- a/crates/skippy-inference-api/Cargo.toml +++ b/crates/skippy-inference-api/Cargo.toml @@ -11,6 +11,7 @@ homepage = "https://github.com/Mesh-LLM/skippy" [dependencies] async-trait = "0.1" axum = { version = "0.8", features = ["multipart", "ws"] } +hex = "0.4" base64 = "0.22" futures-core = "0.3" futures-util = { version = "0.3", features = ["sink"] } diff --git a/crates/skippy-inference-api/src/anthropic/routes.rs b/crates/skippy-inference-api/src/anthropic/routes.rs index e86acb40..e6b2a51f 100644 --- a/crates/skippy-inference-api/src/anthropic/routes.rs +++ b/crates/skippy-inference-api/src/anthropic/routes.rs @@ -81,7 +81,7 @@ async fn non_streaming_messages( request: crate::generation::GenerationRequest, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(&context, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -117,7 +117,7 @@ async fn streaming_messages( ) -> 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(&context, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -252,7 +252,7 @@ pub(crate) async fn messages_count_tokens( ) -> Result, AnthropicRejection> { let Json(request) = json_payload(payload)?; 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, 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_tests.rs b/crates/skippy-inference-api/src/anthropic/translate_tests.rs index 1cd7f188..84cc5b62 100644 --- a/crates/skippy-inference-api/src/anthropic/translate_tests.rs +++ b/crates/skippy-inference-api/src/anthropic/translate_tests.rs @@ -418,6 +418,7 @@ fn delta_chunk(content: Option<&str>, tool_calls: Option) -> }], usage: None, timings: None, + receipt: None, } } diff --git a/crates/skippy-inference-api/src/backend.rs b/crates/skippy-inference-api/src/backend.rs index 7eb213f4..fac90ec4 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>, + receipt: Option, } impl InferenceRequestContext { @@ -133,6 +134,18 @@ impl InferenceRequestContext { self.execution_scope } + /// Carry the receipt binding the request asked for. + pub fn with_receipt(mut self, receipt: Option) -> Self { + self.receipt = receipt; + self + } + + /// The receipt binding the request asked for: the client's VRF key and + /// the parent turn. + pub fn receipt(&self) -> Option { + self.receipt + } + /// 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, + receipt: None, } } } diff --git a/crates/skippy-inference-api/src/chat.rs b/crates/skippy-inference-api/src/chat.rs index 0af37724..428d733f 100644 --- a/crates/skippy-inference-api/src/chat.rs +++ b/crates/skippy-inference-api/src/chat.rs @@ -105,6 +105,10 @@ pub struct ChatCompletionResponse { pub usage: Usage, #[serde(skip_serializing_if = "Option::is_none")] pub timings: Option>, + /// The turn's inference receipt, when the request asked for one with + /// `x-receipt-client-key` and the serving node issues receipts. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option, /// Rung-ladder response-leg marker, minted by /// [`crate::hooks::InferenceHookPolicy::capsule_marker_for_response`]. Never /// serialized into the OpenAI-shaped JSON body — a real `X-Capsule-Id` @@ -206,6 +210,10 @@ pub struct ChatCompletionChunk { pub usage: Option, #[serde(skip_serializing_if = "Option::is_none")] pub timings: Option>, + /// The turn's inference receipt, when the request asked for one with + /// `x-receipt-client-key` and the serving node issues receipts. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option, } impl ChatCompletionChunk { diff --git a/crates/skippy-inference-api/src/chat/generation.rs b/crates/skippy-inference-api/src/chat/generation.rs index b765066b..7583b252 100644 --- a/crates/skippy-inference-api/src/chat/generation.rs +++ b/crates/skippy-inference-api/src/chat/generation.rs @@ -124,6 +124,7 @@ impl From for GenerationResponse { choices: value.choices.into_iter().map(Into::into).collect(), usage: value.usage, timings: value.timings, + receipt: value.receipt, capsule_marker: value.capsule_marker, exchange_id: value.exchange_id, } @@ -140,6 +141,7 @@ impl From for ChatCompletionResponse { choices: value.choices.into_iter().map(Into::into).collect(), usage: value.usage, timings: value.timings, + receipt: value.receipt, capsule_marker: value.capsule_marker, exchange_id: value.exchange_id, } @@ -199,6 +201,7 @@ impl From for GenerationEvent { choices: value.choices.into_iter().map(Into::into).collect(), usage: value.usage, timings: value.timings, + receipt: value.receipt, } } } @@ -213,6 +216,7 @@ impl From for ChatCompletionChunk { choices: value.choices.into_iter().map(Into::into).collect(), usage: value.usage, timings: value.timings, + receipt: value.receipt, } } } diff --git a/crates/skippy-inference-api/src/completions.rs b/crates/skippy-inference-api/src/completions.rs index b0ae185d..8e97c4bb 100644 --- a/crates/skippy-inference-api/src/completions.rs +++ b/crates/skippy-inference-api/src/completions.rs @@ -159,6 +159,10 @@ pub struct CompletionResponse { pub usage: Usage, #[serde(skip_serializing_if = "Option::is_none")] pub timings: Option>, + /// The turn's inference receipt, when the request asked for one with + /// `x-receipt-client-key` and the serving node issues receipts. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option, } impl CompletionResponse { @@ -185,6 +189,7 @@ impl CompletionResponse { }], usage, timings: None, + receipt: None, } } @@ -241,6 +246,10 @@ pub struct CompletionChunk { pub usage: Option, #[serde(skip_serializing_if = "Option::is_none")] pub timings: Option>, + /// The turn's inference receipt, when the request asked for one with + /// `x-receipt-client-key` and the serving node issues receipts. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option, } impl CompletionChunk { @@ -258,6 +267,7 @@ impl CompletionChunk { }], usage: None, timings: None, + receipt: None, } } @@ -279,6 +289,7 @@ impl CompletionChunk { }], usage: None, timings: None, + receipt: None, } } @@ -291,6 +302,7 @@ impl CompletionChunk { choices: Vec::new(), usage: Some(usage), timings: None, + receipt: None, } } diff --git a/crates/skippy-inference-api/src/generation/response.rs b/crates/skippy-inference-api/src/generation/response.rs index 74338a38..eeeb3faf 100644 --- a/crates/skippy-inference-api/src/generation/response.rs +++ b/crates/skippy-inference-api/src/generation/response.rs @@ -17,6 +17,9 @@ pub struct GenerationResponse { pub usage: Usage, pub timings: Option>, + /// The turn's inference receipt, when the request asked for one with + /// `x-receipt-client-key` and the serving node issues receipts. + pub receipt: Option, /// Response attestation metadata consumed by the frontend header adapter. pub capsule_marker: Option, /// Host-minted exchange identity shared with the terminal hook and frontend. @@ -75,6 +78,7 @@ impl GenerationResponse { }], usage, timings: None, + receipt: None, capsule_marker: None, exchange_id: None, } @@ -103,6 +107,7 @@ impl GenerationResponse { choices, usage, timings, + receipt: None, capsule_marker: None, exchange_id: None, } @@ -143,6 +148,8 @@ pub struct GenerationEvent { pub usage: Option, pub timings: Option>, + /// The turn's inference receipt, on the last event of a turn that has one. + pub receipt: Option, } impl GenerationEvent { @@ -164,6 +171,7 @@ impl GenerationEvent { }], usage: None, timings: None, + receipt: None, } } @@ -185,6 +193,7 @@ impl GenerationEvent { }], usage: None, timings: None, + receipt: None, } } @@ -210,6 +219,7 @@ impl GenerationEvent { }], usage: None, timings: None, + receipt: None, } } @@ -221,6 +231,7 @@ impl GenerationEvent { choices: Vec::new(), usage: Some(usage), timings: None, + receipt: None, } } diff --git a/crates/skippy-inference-api/src/guardrails/tests.rs b/crates/skippy-inference-api/src/guardrails/tests.rs index e9bdd533..7c023df7 100644 --- a/crates/skippy-inference-api/src/guardrails/tests.rs +++ b/crates/skippy-inference-api/src/guardrails/tests.rs @@ -1384,6 +1384,7 @@ fn response_with_content_with_usage( }], usage, timings: None, + receipt: None, capsule_marker: None, exchange_id: None, } @@ -1420,6 +1421,7 @@ fn response_with_tool_calls_with_usage( }], usage, timings: None, + receipt: None, capsule_marker: None, exchange_id: None, } diff --git a/crates/skippy-inference-api/src/lib.rs b/crates/skippy-inference-api/src/lib.rs index 1497fd4f..dec38d85 100644 --- a/crates/skippy-inference-api/src/lib.rs +++ b/crates/skippy-inference-api/src/lib.rs @@ -18,6 +18,7 @@ pub mod lifecycle; pub mod model_dispatch; pub mod models; pub mod realtime; +pub mod receipts; mod request_lifecycle; pub mod rerank; pub mod responses; @@ -81,6 +82,10 @@ pub use lifecycle::{ request_id_response_header, }; pub use models::{ModelId, ModelIdError, ModelObject, ModelsResponse}; +pub use receipts::{ + RECEIPT_CLIENT_KEY_HEADER, RECEIPT_ID_HEADER, RECEIPT_PARENT_HEADER, RECEIPT_SEED_HEADER, + ReceiptRequest, +}; pub use rerank::{RerankDocument, RerankRequest, RerankResponse, RerankResult}; pub use responses::{ NormalizationOutcome, ResponseAdapterMode, ResponsesRequest, StreamUsage, diff --git a/crates/skippy-inference-api/src/lifecycle.rs b/crates/skippy-inference-api/src/lifecycle.rs index f2b126b5..7250edf5 100644 --- a/crates/skippy-inference-api/src/lifecycle.rs +++ b/crates/skippy-inference-api/src/lifecycle.rs @@ -10,7 +10,7 @@ use skippy_events::lifecycle::LifecycleState; use skippy_events::usage::TokenUsage; use uuid::Uuid; -use crate::{common::Usage, errors::InferenceError}; +use crate::{common::Usage, errors::InferenceError, receipts::ReceiptRequest}; /// The canonical request correlation header used by the inference frontend. pub static REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id"); @@ -42,6 +42,9 @@ pub struct InferenceLifecycleContext { pub request_id: RequestId, pub method: InferenceRequestMethod, pub route: InferenceFrontendRoute, + /// The receipt binding the request's headers ask for + /// ([`ReceiptRequest::from_headers`]). + pub receipt: Option, } impl InferenceLifecycleContext { @@ -54,8 +57,14 @@ impl InferenceLifecycleContext { request_id, method, route, + receipt: None, } } + + pub const fn with_receipt(mut self, receipt: Option) -> Self { + self.receipt = receipt; + self + } } /// A bounded HTTP method classification for lifecycle metadata. diff --git a/crates/skippy-inference-api/src/receipts.rs b/crates/skippy-inference-api/src/receipts.rs new file mode 100644 index 00000000..4803b6a0 --- /dev/null +++ b/crates/skippy-inference-api/src/receipts.rs @@ -0,0 +1,184 @@ +//! What a request asks an inference receipt to bind: the request headers +//! that name the client's key and the parent turn, and how they are read. +//! +//! The frontend only carries the binding to the backend +//! ([`crate::InferenceLifecycleContext::receipt`], +//! [`crate::InferenceRequestContext::receipt`]); a serving node that issues +//! receipts commits the turn and puts the receipt in the response's +//! `receipt` field. + +use axum::http::{HeaderMap, header::HeaderName}; + +/// The client's VRF key for an inference receipt, 64 hex digits. A serving +/// node that issues receipts binds it into the turn, so the client is bound +/// to its key before it sees what it will challenge. +pub static RECEIPT_CLIENT_KEY_HEADER: HeaderName = HeaderName::from_static("x-receipt-client-key"); +/// The turn root of the receipt this request continues, 64 hex digits. +pub static RECEIPT_PARENT_HEADER: HeaderName = HeaderName::from_static("x-receipt-parent"); +/// The seed the client asks a sampled turn to draw with, a decimal `u32` above +/// 0. A serving node that issues receipts uses it when the request body sets +/// no seed of its own, and states the seed it used, so the client can replay +/// the draw with a seed the node did not choose. Unlike a seed in the body, +/// it does not turn sampling on for a request that would decode greedily. +pub static RECEIPT_SEED_HEADER: HeaderName = HeaderName::from_static("x-receipt-seed"); +/// The id the client asks the turn's receipt to be issued under, a UUID. A +/// serving node that issues receipts uses it instead of the request's +/// `x-request-id`, so a client that names a fresh one for every attempt +/// never finds its id taken by another turn. A node that does not know the +/// header uses `x-request-id`, as before. +pub static RECEIPT_ID_HEADER: HeaderName = HeaderName::from_static("x-receipt-id"); + +/// What a request asks a receipt to bind. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReceiptRequest { + pub client_key: [u8; 32], + pub parent: Option<[u8; 32]>, + /// The seed the client asks a sampled turn to draw with. + pub seed: Option, + /// The id the client asks the receipt to be issued under + /// ([`RECEIPT_ID_HEADER`]): one well-formed UUID, else none. + pub id: Option, +} + +impl ReceiptRequest { + /// The receipt binding a request asks for: a well-formed client key, and + /// the parent turn root when it names a well-formed one. + pub fn from_headers(headers: &HeaderMap) -> Option { + let key = |name: &HeaderName| { + let text = headers.get(name)?.to_str().ok()?; + let bytes = hex::decode(text.trim()).ok()?; + <[u8; 32]>::try_from(bytes.as_slice()).ok() + }; + Some(Self { + client_key: key(&RECEIPT_CLIENT_KEY_HEADER)?, + parent: key(&RECEIPT_PARENT_HEADER), + seed: headers + .get(&RECEIPT_SEED_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|text| text.trim().parse::().ok()) + .filter(|seed| *seed != 0), + id: single_uuid(headers, &RECEIPT_ID_HEADER), + }) + } +} + +/// The one value of `name` in `headers`, when it is a UUID. Two values, or +/// one that is not a UUID, name none. +fn single_uuid(headers: &HeaderMap, name: &HeaderName) -> Option { + let mut values = headers.get_all(name).iter(); + let (Some(value), None) = (values.next(), values.next()) else { + return None; + }; + uuid::Uuid::parse_str(value.to_str().ok()?.trim()).ok() +} + +/// The responses and stream events that carry a turn's receipt in their +/// `receipt` field. +macro_rules! carries_receipt { + ($($response:ty),+ $(,)?) => {$( + impl $response { + /// Carries the turn's inference receipt, when there is one. + pub fn with_receipt(mut self, receipt: Option) -> Self { + self.receipt = receipt; + self + } + } + )+}; +} + +carries_receipt!( + crate::chat::ChatCompletionResponse, + crate::chat::ChatCompletionChunk, + crate::completions::CompletionResponse, + crate::completions::CompletionChunk, + crate::generation::GenerationResponse, + crate::generation::GenerationEvent, +); + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::chat::{ChatCompletionChunk, ChatCompletionResponse}; + use crate::common::Usage; + + #[test] + fn the_receipt_request_reads_its_headers() { + use axum::http::{HeaderMap, HeaderValue}; + + let key = "ab".repeat(32); + let mut headers = HeaderMap::new(); + assert_eq!(super::ReceiptRequest::from_headers(&headers), None); + headers.insert( + &super::RECEIPT_CLIENT_KEY_HEADER, + HeaderValue::from_str(&key).unwrap(), + ); + let plain = super::ReceiptRequest::from_headers(&headers).expect("a request"); + assert_eq!(plain.client_key, [0xab; 32]); + assert_eq!((plain.parent, plain.seed), (None, None)); + // a seed is a decimal u32 above 0; anything else names none + for (text, seed) in [ + ("77", Some(77)), + (" 4294967295 ", Some(u32::MAX)), + ("0", None), + ("4294967296", None), + ("-1", None), + ("0x10", None), + ] { + headers.insert( + &super::RECEIPT_SEED_HEADER, + HeaderValue::from_str(text).unwrap(), + ); + let request = super::ReceiptRequest::from_headers(&headers).expect("a request"); + assert_eq!(request.seed, seed, "{text:?}"); + } + // a receipt id is one UUID; anything else names none + assert_eq!( + super::ReceiptRequest::from_headers(&headers).unwrap().id, + None + ); + let id = "0b0e7c1e-58a5-4b3f-9c36-0d2f6f1f8a10"; + for (values, named) in [ + (vec![id], true), + (vec![" 0B0E7C1E-58A5-4B3F-9C36-0D2F6F1F8A10 "], true), + (vec!["r-1"], false), + (vec![id, id], false), + ] { + headers.remove(&super::RECEIPT_ID_HEADER); + for value in &values { + headers.append( + &super::RECEIPT_ID_HEADER, + HeaderValue::from_str(value).unwrap(), + ); + } + let request = super::ReceiptRequest::from_headers(&headers).expect("a request"); + let expected = named.then(|| uuid::Uuid::parse_str(id).unwrap()); + assert_eq!(request.id, expected, "{values:?}"); + } + // a seed without a key asks for no receipt + headers.remove(&super::RECEIPT_CLIENT_KEY_HEADER); + assert_eq!(super::ReceiptRequest::from_headers(&headers), None); + } + + #[test] + fn the_receipt_rides_only_when_there_is_one() { + let done = ChatCompletionChunk::done("model"); + assert!( + serde_json::to_value(&done) + .unwrap() + .get("receipt") + .is_none() + ); + let done = done.with_receipt(Some(json!({"receipt_id": "r"}))); + assert_eq!( + serde_json::to_value(done).unwrap()["receipt"]["receipt_id"], + "r" + ); + let response = ChatCompletionResponse::new("model", "text", Usage::new(1, 1)) + .with_receipt(Some(json!({"receipt_id": "r"}))); + assert_eq!( + serde_json::to_value(response).unwrap()["receipt"]["receipt_id"], + "r" + ); + } +} diff --git a/crates/skippy-inference-api/src/responses.rs b/crates/skippy-inference-api/src/responses.rs index 5253322a..5d5ad0bb 100644 --- a/crates/skippy-inference-api/src/responses.rs +++ b/crates/skippy-inference-api/src/responses.rs @@ -1184,6 +1184,7 @@ mod tests { }], usage: Usage::new(6, 3), timings: None, + receipt: None, capsule_marker: None, exchange_id: None, }) diff --git a/crates/skippy-inference-api/src/router.rs b/crates/skippy-inference-api/src/router.rs index 04a21ff3..1ead07a1 100644 --- a/crates/skippy-inference-api/src/router.rs +++ b/crates/skippy-inference-api/src/router.rs @@ -636,7 +636,7 @@ async fn completions( 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, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -680,7 +680,7 @@ 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, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -788,11 +788,12 @@ fn resolve_agent_session( } pub(crate) fn request_context( - request_id: RequestId, + lifecycle: &InferenceLifecycleContext, 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(lifecycle.request_id) + .with_receipt(lifecycle.receipt); if trusted_agent_session { context = context.with_trusted_agent_session(); } @@ -868,7 +869,10 @@ async fn frontend_lifecycle_middleware( request_id, lifecycle_method(&method), lifecycle_route(&uri), - ); + ) + .with_receipt(crate::receipts::ReceiptRequest::from_headers( + request.headers(), + )); request.extensions_mut().insert(request_id); request.extensions_mut().insert(context.clone()); let mut lifecycle = diff --git a/crates/skippy-inference-api/src/router/generation.rs b/crates/skippy-inference-api/src/router/generation.rs index d9500a01..08ff5168 100644 --- a/crates/skippy-inference-api/src/router/generation.rs +++ b/crates/skippy-inference-api/src/router/generation.rs @@ -17,7 +17,7 @@ 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, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -72,7 +72,7 @@ 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, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -144,7 +144,7 @@ async fn stream_responses( 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, 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( @@ -197,7 +197,7 @@ async fn non_streaming_responses( request: GenerationRequest, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(context, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), context, diff --git a/crates/skippy-inference-api/src/router_tests.rs b/crates/skippy-inference-api/src/router_tests.rs index 660c0ed7..3ba8a5e5 100644 --- a/crates/skippy-inference-api/src/router_tests.rs +++ b/crates/skippy-inference-api/src/router_tests.rs @@ -331,6 +331,7 @@ impl InferenceBackend for GuardrailRescueBackend { }], usage: Usage::new(3, 2), timings: None, + receipt: None, capsule_marker: None, exchange_id: None, }) @@ -596,6 +597,7 @@ impl InferenceBackend for FakeBackend { }], usage: Usage::new(3, 2), timings: None, + receipt: None, capsule_marker: None, exchange_id: None, }); @@ -659,6 +661,7 @@ impl InferenceBackend for FakeBackend { }], usage: None, timings: None, + receipt: None, }), Ok(GenerationEvent::done(model)), ]))); diff --git a/crates/skippy-inference-api/tests/anthropic_contract.rs b/crates/skippy-inference-api/tests/anthropic_contract.rs index ba5b0749..cad45260 100644 --- a/crates/skippy-inference-api/tests/anthropic_contract.rs +++ b/crates/skippy-inference-api/tests/anthropic_contract.rs @@ -366,6 +366,7 @@ fn tool_call_chunk( }], usage: None, timings: None, + receipt: None, } } diff --git a/crates/skippy-model-hf/src/cache_paths.rs b/crates/skippy-model-hf/src/cache_paths.rs index 44f6607e..0390813f 100644 --- a/crates/skippy-model-hf/src/cache_paths.rs +++ b/crates/skippy-model-hf/src/cache_paths.rs @@ -90,10 +90,17 @@ pub fn huggingface_xet_cache_dir() -> PathBuf { } pub fn application_cache_dir() -> PathBuf { + user_application_cache_dir() + .unwrap_or_else(|| std::env::temp_dir().join("skippy-cache").join("skippy")) +} + +/// The application's directory under the user's own cache directory, or +/// `None` when the process has no home or cache directory. Unlike +/// [`application_cache_dir`], never under the shared temporary directory. +pub fn user_application_cache_dir() -> Option { dirs::cache_dir() .or_else(|| dirs::home_dir().map(|home| home.join(".cache"))) - .unwrap_or_else(|| std::env::temp_dir().join("skippy-cache")) - .join("skippy") + .map(|dir| dir.join("skippy")) } pub fn prepare_download_directories() -> Result { diff --git a/crates/skippy-model-hf/src/lib.rs b/crates/skippy-model-hf/src/lib.rs index 3ce3ebcd..2897f785 100644 --- a/crates/skippy-model-hf/src/lib.rs +++ b/crates/skippy-model-hf/src/lib.rs @@ -18,6 +18,7 @@ pub use cache_paths::{ application_cache_dir, download_cache_diagnostic, download_cache_diagnostic_for, huggingface_hub_cache_dir, huggingface_xet_cache_dir, prepare_cli_download_directories, prepare_download_directories, prepare_download_directories_with_data_roots, + user_application_cache_dir, }; pub use checkpoint::DownloadedCheckpointFile; pub use tls::{HfTlsProvider, configure_hf_tls_provider}; diff --git a/crates/skippy-protocol/README.md b/crates/skippy-protocol/README.md index 30fb1818..da2f80f9 100644 --- a/crates/skippy-protocol/README.md +++ b/crates/skippy-protocol/README.md @@ -65,8 +65,11 @@ 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 prefill chunk of a wide boundary crosses as one frame; a chunk whose output -still exceeds the budget is sent as consecutive prefill frames. All -participants must advertise `stage-generation-17`; older peers fail closed. +still exceeds the budget is sent as consecutive prefill frames. + +Generation 18 adds `issue_receipts` to the stage load: a later stage of a +binary split records its part of the inference receipts that stage 0 issues. +All participants must advertise `stage-generation-18`; older peers fail closed. 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/proto/stage.proto b/crates/skippy-protocol/proto/stage.proto index 78aaefd2..aeee206b 100644 --- a/crates/skippy-protocol/proto/stage.proto +++ b/crates/skippy-protocol/proto/stage.proto @@ -112,6 +112,10 @@ message LoadStage { // its target layers capture that layer's input and forward it with their // activations; the final stage drafts. Older stages ignore it. optional StageDFlashPlan dflash = 53; + // Record this stage's part of inference receipts, which stage 0 issues. + // Stage 0 commits and opens it over a receipts connection to this + // stage's binary address. + bool issue_receipts = 54; } message StageDFlashPlan { diff --git a/crates/skippy-protocol/src/binary/codec.rs b/crates/skippy-protocol/src/binary/codec.rs index 254f9f9a..e713b0ee 100644 --- a/crates/skippy-protocol/src/binary/codec.rs +++ b/crates/skippy-protocol/src/binary/codec.rs @@ -187,9 +187,40 @@ pub fn send_reply_message(mut writer: impl Write, reply: &StageReply) -> io::Res Ok(()) } +/// The bound on the body a message kind carries in `raw_bytes`, and how +/// its violations read. +pub(super) struct RawBytes { + pub(super) max: usize, + pub(super) mismatch: &'static str, + pub(super) too_large: &'static str, + pub(super) count_too_large: &'static str, + pub(super) over_budget: &'static str, +} + +impl RawBytes { + fn of(kind: WireMessageKind) -> Self { + if kind == WireMessageKind::Receipts { + super::receipts::REQUEST_BODY + } else { + Self { + max: MAX_STAGE_STATE_IMPORT_BYTES, + mismatch: "state import raw byte count mismatch", + too_large: "state import raw byte count exceeds maximum", + count_too_large: "state import byte count exceeds maximum", + over_budget: "state import byte count exceeds frame budget", + } + } + } +} + /// Decode and validate a typed reply before exposing its payload to the caller. pub fn recv_reply(mut reader: impl Read) -> io::Result { let kind = WireReplyKind::try_from(read_i32(&mut reader)?)?; + if kind == WireReplyKind::Receipts { + return Err(invalid_data( + "a receipts reply is read by recv_receipts_reply", + )); + } let predicted = read_i32(&mut reader)?; let predicted_count = checked_i32_len( read_i32(&mut reader)?, @@ -410,14 +441,15 @@ pub fn write_stage_message(mut writer: impl Write, message: &StageWireMessage) - if message.kind == WireMessageKind::PrefillReadout { super::readout::write_tokens(&mut writer, &message.readout_tokens)?; } - if message.kind == WireMessageKind::StateImport { - let raw_byte_count = usize::try_from(message.token_count) - .map_err(|_| invalid_input("state import raw byte count mismatch"))?; + if message.kind.carries_raw_bytes() { + let limits = RawBytes::of(message.kind); + let raw_byte_count = + usize::try_from(message.token_count).map_err(|_| invalid_input(limits.mismatch))?; if raw_byte_count != message.raw_bytes.len() { - return Err(invalid_input("state import raw byte count mismatch")); + return Err(invalid_input(limits.mismatch)); } - if raw_byte_count > MAX_STAGE_STATE_IMPORT_BYTES { - return Err(invalid_input("state import raw byte count exceeds maximum")); + if raw_byte_count > limits.max { + return Err(invalid_input(limits.too_large)); } writer.write_all(&message.raw_bytes)?; return Ok(()); @@ -609,18 +641,19 @@ fn read_stage_message_inner( + position_sideband_count * std::mem::size_of::(), "sideband value count exceeds frame budget", )?; - if kind == WireMessageKind::StateImport { + if kind.carries_raw_bytes() { + let limits = RawBytes::of(kind); let raw_byte_count = checked_i32_len( token_count, - MAX_STAGE_STATE_IMPORT_BYTES, + limits.max, "negative wire count", - "state import byte count exceeds maximum", + limits.count_too_large, )?; admit_frame_bytes( &frame_budget, &mut frame_used, raw_byte_count, - "state import byte count exceeds frame budget", + limits.over_budget, )?; let mut raw_bytes = vec![0; raw_byte_count]; reader.read_exact(&mut raw_bytes)?; @@ -1073,13 +1106,13 @@ fn write_i32_slice(mut writer: impl Write, values: &[i32]) -> io::Result<()> { Ok(()) } -fn read_i32(mut reader: impl Read) -> io::Result { +pub(super) fn read_i32(mut reader: impl Read) -> io::Result { let mut bytes = [0_u8; 4]; reader.read_exact(&mut bytes)?; Ok(i32::from_le_bytes(bytes)) } -fn write_i32(mut writer: impl Write, value: i32) -> io::Result<()> { +pub(super) fn write_i32(mut writer: impl Write, value: i32) -> io::Result<()> { writer.write_all(&value.to_le_bytes()) } @@ -1093,13 +1126,13 @@ fn write_i64(mut writer: impl Write, value: i64) -> io::Result<()> { writer.write_all(&value.to_le_bytes()) } -fn read_u32(mut reader: impl Read) -> io::Result { +pub(super) fn read_u32(mut reader: impl Read) -> io::Result { let mut bytes = [0_u8; 4]; reader.read_exact(&mut bytes)?; Ok(u32::from_le_bytes(bytes)) } -fn write_u32(mut writer: impl Write, value: u32) -> io::Result<()> { +pub(super) fn write_u32(mut writer: impl Write, value: u32) -> io::Result<()> { writer.write_all(&value.to_le_bytes()) } diff --git a/crates/skippy-protocol/src/binary/mod.rs b/crates/skippy-protocol/src/binary/mod.rs index 6ba1b554..0b2930be 100644 --- a/crates/skippy-protocol/src/binary/mod.rs +++ b/crates/skippy-protocol/src/binary/mod.rs @@ -2,10 +2,13 @@ mod activation; mod activation_codec; mod codec; mod readout; +mod receipts; mod types; #[cfg(test)] mod frame_budget_tests; +#[cfg(test)] +mod receipts_reply_tests; pub use activation::{ activation_frame_wire_bytes, decode_activation_frame, decode_raw_activation_frame, @@ -20,6 +23,10 @@ pub use codec::{ send_reply_predicted_with_stats, send_reply_predicted_with_tokens_and_stats, send_reply_predicted_with_tokens_window_and_stats, write_stage_message, }; +pub use receipts::{ + MAX_STAGE_RECEIPTS_REFUSAL_BYTES, MAX_STAGE_RECEIPTS_REPLY_BYTES, + MAX_STAGE_RECEIPTS_REQUEST_BYTES, ReceiptsReply, recv_receipts_reply, send_receipts_reply, +}; pub use types::sampling_flags; pub use types::{ LLAMA_TOKEN_NULL, MAX_STAGE_ACTIVATION_BYTES, MAX_STAGE_ACTIVATION_DIMS, diff --git a/crates/skippy-protocol/src/binary/receipts.rs b/crates/skippy-protocol/src/binary/receipts.rs new file mode 100644 index 00000000..c735b02b --- /dev/null +++ b/crates/skippy-protocol/src/binary/receipts.rs @@ -0,0 +1,155 @@ +//! The receipts messages of the stage connection: a request with a JSON +//! body ([`WireMessageKind::Receipts`]), and a reply that says what kind of +//! answer it is ([`WireReplyKind::Receipts`]) and is read only up to what +//! its request can produce. + +use std::io::{self, Read, Write}; + +use super::codec::{RawBytes, read_i32, read_u32, write_i32, write_u32}; +use super::{ + StageStateHeader, StageWireMessage, WireMessageKind, WireReplyKind, invalid_data, invalid_input, +}; + +/// A receipts request: a JSON commit or challenge. +pub const MAX_STAGE_RECEIPTS_REQUEST_BYTES: usize = 1024 * 1024; +/// The most a receipts reply can hold. A stage that waits for one bounds it +/// further, by what its own request can produce ([`recv_receipts_reply`]). +pub const MAX_STAGE_RECEIPTS_REPLY_BYTES: usize = 256 * 1024 * 1024; +/// A receipts reply that is not an answer: why a stage refused, or its +/// "cannot open" result. +pub const MAX_STAGE_RECEIPTS_REFUSAL_BYTES: usize = 64 * 1024; + +/// The bound on a receipts request's body in `raw_bytes`, and how its +/// violations read. +pub(super) const REQUEST_BODY: RawBytes = RawBytes { + max: MAX_STAGE_RECEIPTS_REQUEST_BYTES, + mismatch: "receipts request byte count mismatch", + too_large: "receipts request byte count exceeds maximum", + count_too_large: "receipts request byte count exceeds maximum", + over_budget: "receipts request byte count exceeds frame budget", +}; + +/// A stage's reply to a receipts request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReceiptsReply { + /// The JSON answer: commitments, an opening or rows. + Answer(Vec), + /// Why the stage refused the request. + Refused(String), + /// The stage knows no receipt of that id, and why. + NotFound(String), + /// The stage can no longer open the turn, though the request is one it + /// would answer: its JSON "cannot open" result. + CannotOpen(Vec), + /// The stage issues no receipts, and why: asking it again is no use. + Unavailable(String), +} + +impl ReceiptsReply { + fn status(&self) -> u32 { + match self { + Self::Answer(_) => 0, + Self::Refused(_) => 1, + Self::NotFound(_) => 2, + Self::CannotOpen(_) => 3, + Self::Unavailable(_) => 4, + } + } + + fn body(&self) -> &[u8] { + match self { + Self::Answer(body) | Self::CannotOpen(body) => body, + Self::Refused(reason) | Self::NotFound(reason) | Self::Unavailable(reason) => { + reason.as_bytes() + } + } + } + + fn from_wire(status: u32, body: Vec) -> io::Result { + let text = |body: Vec| String::from_utf8_lossy(&body).into_owned(); + match status { + 0 => Ok(Self::Answer(body)), + 1 => Ok(Self::Refused(text(body))), + 2 => Ok(Self::NotFound(text(body))), + 3 => Ok(Self::CannotOpen(body)), + 4 => Ok(Self::Unavailable(text(body))), + _ => Err(invalid_data("unknown receipts reply status")), + } + } +} + +impl StageWireMessage { + /// A receipts request with a JSON `body`, for the stage that receives it + /// and every later one. + pub fn receipts(body: Vec) -> Self { + Self { + kind: WireMessageKind::Receipts, + pos_start: 0, + token_count: i32::try_from(body.len()).unwrap_or(i32::MAX), + state: StageStateHeader::new(WireMessageKind::Receipts), + request_id: 0, + session_id: 0, + sampling: None, + chat_sampling_metadata: None, + tokens: Vec::new(), + positions: Vec::new(), + activation: Vec::new(), + readout_tokens: Vec::new(), + raw_bytes: body, + } + } +} + +/// Sends a stage's reply to a receipts request. +pub fn send_receipts_reply(mut writer: impl Write, reply: &ReceiptsReply) -> io::Result<()> { + let body = reply.body(); + let max = match reply { + ReceiptsReply::Answer(_) => MAX_STAGE_RECEIPTS_REPLY_BYTES, + _ => MAX_STAGE_RECEIPTS_REFUSAL_BYTES, + }; + if body.len() > max { + return Err(invalid_input("receipts reply exceeds maximum")); + } + write_i32(&mut writer, WireReplyKind::Receipts as i32)?; + write_u32(&mut writer, reply.status())?; + write_u32( + &mut writer, + u32::try_from(body.len()).map_err(|_| invalid_input("receipts reply exceeds maximum"))?, + )?; + writer.write_all(body) +} + +/// Reads a stage's reply to a receipts request, whose answer may hold at +/// most `max_answer_bytes`: what the request can produce, as its sender +/// bounds it. A longer answer is refused from its declared length, before +/// any of it is read. The body grows with the bytes that arrive, so a +/// declared length alone allocates nothing. +pub fn recv_receipts_reply( + mut reader: impl Read, + max_answer_bytes: usize, +) -> io::Result { + if WireReplyKind::try_from(read_i32(&mut reader)?)? != WireReplyKind::Receipts { + return Err(invalid_data("expected a receipts reply")); + } + let status = read_u32(&mut reader)?; + let len = usize::try_from(read_u32(&mut reader)?) + .map_err(|_| invalid_data("receipts reply exceeds maximum"))?; + let max = match status { + 0 => max_answer_bytes.min(MAX_STAGE_RECEIPTS_REPLY_BYTES), + _ => MAX_STAGE_RECEIPTS_REFUSAL_BYTES, + }; + if len > max { + return Err(invalid_data( + "receipts reply exceeds what its request can produce", + )); + } + let mut body = Vec::new(); + let read = (&mut reader).take(len as u64).read_to_end(&mut body)?; + if read != len { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "receipts reply ended early", + )); + } + ReceiptsReply::from_wire(status, body) +} diff --git a/crates/skippy-protocol/src/binary/receipts_reply_tests.rs b/crates/skippy-protocol/src/binary/receipts_reply_tests.rs new file mode 100644 index 00000000..87762e9b --- /dev/null +++ b/crates/skippy-protocol/src/binary/receipts_reply_tests.rs @@ -0,0 +1,66 @@ +//! The receipts messages of the stage connection: a request with a JSON +//! body, and a reply that says what kind of answer it is and is read only +//! up to what its request can produce. + +use super::*; +use std::io::Cursor; + +/// A receipts request carries its JSON body, and its reply is read +/// only as a receipts reply. +#[test] +fn receipts_messages_round_trip() { + let message = StageWireMessage::receipts(br#"{"commit":{}}"#.to_vec()); + let mut bytes = Vec::new(); + write_stage_message(&mut bytes, &message).unwrap(); + let decoded = read_stage_message(Cursor::new(bytes), 2048).unwrap(); + assert_eq!(decoded.kind, WireMessageKind::Receipts); + assert_eq!(decoded.raw_bytes, br#"{"commit":{}}"#.to_vec()); + + let mut reply = Vec::new(); + let answer = ReceiptsReply::Answer(b"[1]".to_vec()); + send_receipts_reply(&mut reply, &answer).unwrap(); + assert_eq!( + recv_receipts_reply(Cursor::new(reply.clone()), 3).unwrap(), + answer + ); + assert!(recv_reply(Cursor::new(reply.clone())).is_err()); + reply.truncate(reply.len() - 1); + assert!(recv_receipts_reply(Cursor::new(reply), 3).is_err()); + + for other in [ + ReceiptsReply::Refused("no turn".into()), + ReceiptsReply::NotFound("no receipt r1".into()), + ReceiptsReply::CannotOpen(br#"{"reason":"expired"}"#.to_vec()), + ReceiptsReply::Unavailable("receipts are off".into()), + ] { + let mut bytes = Vec::new(); + send_receipts_reply(&mut bytes, &other).unwrap(); + // what is not an answer is not held to the answer's bound + assert_eq!(recv_receipts_reply(Cursor::new(bytes), 0).unwrap(), other); + } + let mut ack = Vec::new(); + send_reply_ack(&mut ack).unwrap(); + assert!(recv_receipts_reply(Cursor::new(ack), 3).is_err()); +} + +/// A reply longer than its request can produce is refused from its +/// declared length: the stage that asked reads none of it. +#[test] +fn a_receipts_reply_is_bounded_by_its_request() { + let mut reply = Vec::new(); + send_receipts_reply(&mut reply, &ReceiptsReply::Answer(vec![b'x'; 1000])).unwrap(); + assert!(recv_receipts_reply(Cursor::new(reply.clone()), 1000).is_ok()); + let error = recv_receipts_reply(Cursor::new(reply), 999).unwrap_err(); + assert!(error.to_string().contains("exceeds"), "{error}"); + + // a declared length alone is refused, with no body behind it + let mut declared = Vec::new(); + declared.extend_from_slice(&(WireReplyKind::Receipts as i32).to_le_bytes()); + declared.extend_from_slice(&0u32.to_le_bytes()); + declared.extend_from_slice(&u32::MAX.to_le_bytes()); + let error = recv_receipts_reply(Cursor::new(declared), usize::MAX).unwrap_err(); + assert!(error.to_string().contains("exceeds"), "{error}"); + + let long = ReceiptsReply::Refused("x".repeat(MAX_STAGE_RECEIPTS_REFUSAL_BYTES + 1)); + assert!(send_receipts_reply(Vec::new(), &long).is_err()); +} diff --git a/crates/skippy-protocol/src/binary/types.rs b/crates/skippy-protocol/src/binary/types.rs index f5d323b8..ac9e1308 100644 --- a/crates/skippy-protocol/src/binary/types.rs +++ b/crates/skippy-protocol/src/binary/types.rs @@ -58,6 +58,9 @@ pub enum WireMessageKind { TryRestorePrefillDecode = 18, TrimSession = 19, PredictionReturnOpen = 20, + /// A receipts commit or open for this stage and every later one; the + /// body is in `raw_bytes`, and the reply is a [`WireReplyKind::Receipts`]. + Receipts = 25, } impl WireMessageKind { @@ -85,6 +88,16 @@ impl WireMessageKind { ) } + pub fn is_receipts(self) -> bool { + matches!(self, Self::Receipts) + } + + /// Kinds whose body is opaque bytes in `raw_bytes`, counted by + /// `token_count`. + pub fn carries_raw_bytes(self) -> bool { + matches!(self, Self::StateImport | Self::Receipts) + } + pub fn is_session_control(self) -> bool { matches!(self, Self::TrimSession) } @@ -150,6 +163,7 @@ impl TryFrom for WireMessageKind { 22 => Ok(Self::RetireVerifyWindow), 23 => Ok(Self::DiscardStaleWindows), 24 => Ok(Self::PrefillReadout), + 25 => Ok(Self::Receipts), _ => Err(invalid_data("unknown stage message kind")), } } @@ -162,6 +176,8 @@ pub enum WireReplyKind { PredictedToken = 2, PredictedTokens = 3, TokenScores = 4, + /// The body of a receipts reply ([`super::send_receipts_reply`]). + Receipts = 5, } impl TryFrom for WireReplyKind { @@ -174,6 +190,7 @@ impl TryFrom for WireReplyKind { 2 => Ok(Self::PredictedToken), 3 => Ok(Self::PredictedTokens), 4 => Ok(Self::TokenScores), + 5 => Ok(Self::Receipts), _ => Err(invalid_data("unknown stage reply kind")), } } @@ -323,6 +340,9 @@ pub struct StageSamplingConfig { pub mod sampling_flags { pub const ENABLED: u32 = 1 << 0; pub const IGNORE_EOS: u32 = 1 << 1; + /// The final stage draws each sampled token with the indexed draw of a + /// receipted turn, which a client can replay. + pub const INDEXED_DRAW: u32 = 1 << 3; } impl Default for StageSamplingConfig { @@ -481,6 +501,7 @@ impl StageStateHeader { || kind.is_verify_retirement() || kind.is_stale_window_discard() || kind.is_generation_control() + || kind.is_receipts() { return true; } @@ -615,7 +636,7 @@ impl StageWireMessage { } fn payload_wire_bytes(&self) -> usize { - if self.kind == WireMessageKind::StateImport { + if self.kind.carries_raw_bytes() { return self.raw_bytes.len(); } self.tokens @@ -975,6 +996,7 @@ fn expected_phase(kind: WireMessageKind) -> WireStagePhase { || kind.is_verify_retirement() || kind.is_generation_control() || kind.is_prefix_cache_control() + || kind.is_receipts() { WireStagePhase::Prefill } else if kind.is_decode_replay() { diff --git a/crates/skippy-protocol/src/lib.rs b/crates/skippy-protocol/src/lib.rs index 639b2af3..e8794395 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_V17, STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, 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_V17, + STAGE_PROTOCOL_GENERATION, STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, 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_V17, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, format!("stage-generation-{STAGE_PROTOCOL_GENERATION}") ); } diff --git a/crates/skippy-protocol/src/validation.rs b/crates/skippy-protocol/src/validation.rs index 638c4032..038c7c4d 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 = 17; +pub const STAGE_PROTOCOL_GENERATION: u32 = 18; /// 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_V17: &str = "stage-generation-17"; +pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18: &str = "stage-generation-18"; pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_GENERATION: &str = - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17; + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18; 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-receipt-audit/Cargo.toml b/crates/skippy-receipt-audit/Cargo.toml new file mode 100644 index 00000000..f9b05497 --- /dev/null +++ b/crates/skippy-receipt-audit/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "skippy-receipt-audit" +edition.workspace = true +license.workspace = true +version.workspace = true +description = "Audits a Skippy inference receipt against a claimed GGUF: the claimed file, native layer loading, the checks of an opening, and the report" +repository = "https://github.com/Mesh-LLM/mesh-llm" +homepage = "https://github.com/Mesh-LLM/mesh-llm" +readme = "README.md" + +[lib] +name = "skippy_receipt_audit" +path = "src/lib.rs" + +[dependencies] +anyhow.workspace = true +hex = "0.4" +rand = "0.10" +reqwest = { version = "0.13", default-features = false, features = ["blocking", "rustls"] } +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +skippy-model-artifact = { path = "../skippy-model-artifact", version = "0.80.0" } +skippy-model-hf = { path = "../skippy-model-hf", version = "0.80.0" } +skippy-model-ref = { path = "../skippy-model-ref", version = "0.80.0" } +skippy-receipts = { path = "../skippy-receipts", version = "0.80.0" } +skippy-runtime = { path = "../skippy-runtime", version = "0.80.0" } + +[dev-dependencies] +# The toy model and honest turn the audit's tests run on. +skippy-receipts = { path = "../skippy-receipts", version = "0.80.0", features = ["test-support"] } +tempfile = "3" + +[lints] +workspace = true diff --git a/crates/skippy-receipt-audit/README.md b/crates/skippy-receipt-audit/README.md new file mode 100644 index 00000000..3672c53f --- /dev/null +++ b/crates/skippy-receipt-audit/README.md @@ -0,0 +1,54 @@ +# skippy-receipt-audit + +Audits one turn that a client received against the GGUF that the node +claims to serve. The checks themselves, the wire shapes and the VRF are in +[`skippy-receipts`](../skippy-receipts/README.md). This crate runs them on +a real model. It opens the claimed file, loads its layers with the native +runtime, asks the node to open the challenge, and adds the results up to +an outcome and a report. + +The design is in [RECEIPTS.md](../../docs/design/RECEIPTS.md) and +[RECEIPTS_GLUE.md](../../docs/design/RECEIPTS_GLUE.md). The feature +is experimental. To serve and audit receipts, see +[docs/RECEIPTS.md](../../docs/RECEIPTS.md). + +## What the crate owns + +| Module | Responsibility | +|---|---| +| `turn_audit` | The audit of one received turn: the binding, the challenge that the VRF draws, the opening that the node signs, and the outcome. `OpenChallenge` is how the caller sends the challenge to the node | +| `recheck` | Runs the same checks again on the evidence that an audit kept | +| `opening_checks` | Every check of an opened turn: the glue and weight rows of each picked layer, the input of layer 0, the output head, the tokens and the recurrent regions | +| `attention_audit` | The attention check, and the second request for the K and V rows | +| `recurrent_audit` | The recurrent check | +| `token_check` | The response and the prompt against the tokens that the receipt names | +| `claimed_model` | `ClaimedModel`, the claimed GGUF as an audit needs it, and the KV cache types of a layer | +| `native_model` | `ClaimedModel` over libllama: one layer at a time on the CPU | +| `claimed_file` | Opens the claimed GGUF, either a local file or `repo@revision/file` on Hugging Face read by range into a sparse copy | +| `head_key_file` | Where the client keeps its secret head key for a model, readable by its owner alone | +| `chat_reply` | The reply that the client received for the turn | +| `outcome` | The four ways an audit ends, and what one check found | +| `output` | The report of an audit as JSON types | +| `report_text` | The report of an audit as text | +| `node_text` | Makes text that the node wrote safe to print | + +## What the crate does not own + +- The checks on opened values, the wire shapes, the challenge draw and the + evidence format are in [`skippy-receipts`](../skippy-receipts/README.md). +- The crate sends no chat request and prints nothing. The + `skippy audit-receipt` and `skippy recheck-receipt` commands, their HTTP + calls, the evidence file and the process exit code are in + [`skippy-commands`](../skippy-commands/README.md). +- Which turns a Mesh node audits, the peer transport and what a verdict + costs a peer are in `mesh-llm-host-runtime`. +- The crate has no dependency on `skippy-commands`, on a Mesh crate, or on + clap. + +## Consumers + +- [`skippy-commands`](../skippy-commands/README.md) runs + `skippy audit-receipt` and `skippy recheck-receipt` on it. +- `mesh-llm-host-runtime`, in the mesh-llm repository, audits the turns + that the peers of a Mesh node serve. It supplies its own `OpenChallenge` + over the Mesh transport. diff --git a/crates/skippy-receipt-audit/src/attention_audit.rs b/crates/skippy-receipt-audit/src/attention_audit.rs new file mode 100644 index 00000000..7c397fe9 --- /dev/null +++ b/crates/skippy-receipt-audit/src/attention_audit.rs @@ -0,0 +1,358 @@ +//! The attention check of an audited turn ([`skippy_receipts::attention`]): +//! the partials the node opened with the challenge must combine to the +//! attention output it committed, and the blocks the client then draws +//! from the opening must recompute to those partials from the committed q +//! and the K and V rows the node opens for them. +//! +//! The rows are a second request, so the check can end three ways besides +//! a verdict: the node did not answer it (unanswered), it signed rows that +//! are defective (a failure), or, in a recheck, the evidence holds no rows +//! (incomplete evidence, which is no failure). + +use std::collections::BTreeMap; +use std::io::Write; +use std::time::Instant; + +use anyhow::Result; +use serde::Serialize; +use skippy_receipts::attention::opening::{AttentionPick, BlockChallenge, RowsOpening}; +use skippy_receipts::attention::{AttentionDescriptor, AttentionLayout, layer_layout}; +use skippy_receipts::attention_check::{ + OpenedHead, PARTIAL_TOLERANCE, block_challenge, block_passed, check_blocks, check_partials, + verify_answer, verify_rows, +}; +use skippy_receipts::node_fault::NodeFault; +use skippy_receipts::opened_values::ValidatedOpening; + +use crate::node_text::shown; + +/// Attention rows as the node sent them: decoded, their bytes, and the +/// node's signature of them. +pub struct OpenedRows { + pub rows: RowsOpening, + pub bytes: Vec, + pub signature: Option, + pub seconds: f64, +} + +/// What asking for the rows of the drawn blocks gave. +pub(crate) enum RowsAnswer { + /// Rows the node signed for these blocks. + Signed(OpenedRows), + /// The node gave no usable signed answer: nothing came back, or it was + /// not signed for these blocks. + Unanswered(String), + /// A recheck's evidence holds no rows for these blocks. + Missing(String), + /// Rows the node signed for these blocks that cannot be read: a + /// failure. + Defective(String), +} + +#[derive(Serialize, Default)] +pub struct AttentionOutput { + pub picks: Vec, + /// Seconds from asking for the blocks' rows to receiving them. + pub rows_seconds: Option, + /// Why the rows the node signed are defective: a failure. + pub rows_error: Option, + /// Why the node gave no usable signed answer to the rows request. The + /// blocks were not checked, and that is the node's doing. + pub rows_unanswered: Option, + /// Why a recheck has no rows to check the blocks with: the evidence is + /// incomplete, which says nothing about the node. + pub rows_missing: Option, +} + +#[derive(Serialize)] +pub struct AttentionPickOutput { + pub position: u32, + pub layer: u32, + pub head: Option, + /// Positions the query attends to. + pub context: usize, + /// How far the partials combine from the opened output, relative to + /// its largest value. + pub combine_error: Option, + pub blocks: Vec, + /// The largest error of a recomputed block against the node's partial. + pub block_error: Option, + /// The layer computes no attention, so there is nothing to check. + pub no_attention: bool, + /// Why the check cannot follow the layer's attention; says nothing + /// about the node. + pub unchecked: Option, + /// Why the pick failed. + pub failure: Option, + pub pass: bool, +} + +impl AttentionPickOutput { + fn new(pick: &AttentionPick) -> Self { + Self { + position: pick.position, + layer: pick.layer, + head: None, + context: 0, + combine_error: None, + blocks: Vec::new(), + block_error: None, + no_attention: false, + unchecked: None, + failure: None, + pass: false, + } + } + + fn fail(&mut self, reason: impl Into) { + self.failure = Some(reason.into()); + self.pass = false; + } + + /// Sorts an error of the pick's check by its mark: the node's fault, + /// or a check that cannot run here. + fn stopped(&mut self, error: &anyhow::Error) { + if NodeFault::find(error).is_some() { + self.fail(format!("{error:#}")); + } else { + self.unchecked = Some(format!("{error:#}")); + } + } +} + +impl AttentionOutput { + pub fn failures(&self) -> Vec { + let mut out: Vec = self + .picks + .iter() + .filter_map(|p| { + let failure = p.failure.as_ref()?; + Some(format!( + "attention at position {}, layer {}: {failure}", + p.position, p.layer + )) + }) + .collect(); + if let Some(error) = &self.rows_error { + out.push(format!("attention rows: {error}")); + } + out + } + + /// The picks whose check could not run here. A pick the node left + /// unanswered is not among them: that is the node's doing. + pub fn unchecked(&self) -> Vec { + let mut out: Vec = self + .picks + .iter() + .filter_map(|p| { + Some(format!( + "attention of layer {}: {}", + p.layer, + p.unchecked.as_ref()? + )) + }) + .collect(); + if let Some(reason) = &self.rows_missing { + out.push(format!("attention rows: {reason}")); + } + out + } +} + +/// A head whose partials combined, with what its blocks are checked with. +struct Pending { + pick: usize, + head: OpenedHead, + layout: AttentionLayout, + q: Vec, +} + +/// Runs the attention check: the partials in `opening`, then the rows +/// `open_rows` returns for the blocks drawn from `rows_seed`. The rows +/// are returned as the node sent them, for evidence. +pub(crate) fn check_attention( + opening: &ValidatedOpening<'_>, + layouts: &BTreeMap>, + rows_seed: &[u8], + open_rows: &dyn Fn(&BlockChallenge) -> RowsAnswer, +) -> (AttentionOutput, Option) { + let challenge = opening.challenge(); + let mut output = AttentionOutput::default(); + let mut pending = Vec::new(); + for pick in &challenge.attention { + let mut checked = AttentionPickOutput::new(pick); + match open_head(opening, layouts, pick) { + Ok(Opened::NoAttention) => checked.no_attention = true, + Ok(Opened::Unchecked(reason)) => checked.unchecked = Some(reason), + Ok(Opened::Head(head, layout, q)) => { + checked.head = Some(head.head); + checked.context = head.context.len(); + checked.combine_error = Some(head.combine_error); + if head.passed() { + pending.push(Pending { + pick: output.picks.len(), + head, + layout: *layout, + q, + }); + } else { + checked.fail(format!( + "the partials combine {:.1e} from the output, past {:.1e}", + head.combine_error, + head.tolerance() + )); + } + } + Err(error) => checked.stopped(&error), + } + output.picks.push(checked); + } + if pending.is_empty() { + return (output, None); + } + let heads: Vec = pending.iter().map(|p| p.head.clone()).collect(); + let blocks = block_challenge(&challenge.receipt_id, &heads, rows_seed); + let started = Instant::now(); + let opened = match open_rows(&blocks) { + RowsAnswer::Signed(opened) => opened, + RowsAnswer::Unanswered(reason) => { + output.rows_unanswered = Some(reason); + return (output, None); + } + RowsAnswer::Missing(reason) => { + output.rows_missing = Some(reason); + return (output, None); + } + RowsAnswer::Defective(reason) => { + output.rows_error = Some(reason); + return (output, None); + } + }; + output.rows_seconds = Some(started.elapsed().as_secs_f64()); + let by_layer: BTreeMap = pending + .iter() + .map(|p| (p.layout.layer, p.layout.clone())) + .collect(); + let receipt = opening.receipt(); + let rows = verify_answer(receipt, &blocks, &heads, &opened.rows) + .and_then(|()| verify_rows(receipt, &by_layer, &opened.rows)); + let rows = match rows { + Ok(rows) => rows, + Err(error) => { + // every error of these is a defect of rows the node signed + output.rows_error = Some(format!("{error:#}")); + return (output, Some(opened)); + } + }; + for (pending, pick) in pending.iter().zip(&blocks.picks) { + let checked = &mut output.picks[pending.pick]; + checked.blocks = pick.blocks.clone(); + match check_blocks(&pending.layout, &pending.head, pick, &pending.q, &rows) { + Ok(error) if block_passed(error) => { + checked.block_error = Some(error); + checked.pass = true; + } + Ok(error) => { + checked.block_error = Some(error); + checked.fail(format!( + "a block recomputes {error:.1e} from its partial, past {PARTIAL_TOLERANCE:.0e}" + )); + } + Err(error) => checked.stopped(&error), + } + } + (output, Some(opened)) +} + +enum Opened { + /// The layer computes no attention, and the node opened no partials. + NoAttention, + Unchecked(String), + Head(OpenedHead, Box, Vec), +} + +/// The pick's head after its partials are checked against the output, or +/// why its layer's attention is not checked. An error that blames the +/// node is a failure of the pick. +fn open_head( + opening: &ValidatedOpening<'_>, + layouts: &BTreeMap>, + pick: &AttentionPick, +) -> Result { + let Some(descriptors) = layouts.get(&pick.layer) else { + return Ok(Opened::Unchecked("the layer's glue did not run".into())); + }; + let partials = opening.partials(pick); + let layout = match layer_layout(descriptors) { + Ok(Some(layout)) => layout, + Ok(None) if partials.is_some() => { + return Err(NodeFault::error( + "the node opened partials in a layer that computes no attention", + )); + } + Ok(None) => return Ok(Opened::NoAttention), + Err(reason) => return Ok(Opened::Unchecked(format!("{reason:#}"))), + }; + // a verified opening holds every position an attention pick names + let Some(leaf) = opening.leaf(pick.layer, pick.position) else { + return Ok(Opened::Unchecked( + "the attention position is not a picked one".into(), + )); + }; + let Some(partials) = partials else { + return Err(NodeFault::error("the node opened no partials")); + }; + let head = check_partials(layout, pick, leaf, partials)?; + let q = layout.q_values(&leaf.mixing).map_err(NodeFault::blame)?; + Ok(Opened::Head(head, Box::new(layout.clone()), q)) +} + +pub(crate) fn render(out: &mut dyn Write, attention: &AttentionOutput) -> std::io::Result<()> { + if attention.picks.is_empty() { + return Ok(()); + } + writeln!(out, "attention, per picked head:")?; + for p in &attention.picks { + let what = format!("position {} layer {}", p.position, p.layer); + if p.no_attention { + writeln!(out, " {what:<26} the layer computes no attention")?; + continue; + } + if let Some(reason) = &p.unchecked { + writeln!(out, " {what:<26} cannot check ({})", shown(reason))?; + continue; + } + let verdict = match (p.pass, &p.failure) { + (true, _) => "ok", + (false, Some(_)) => "FAIL", + (false, None) => "not checked", + }; + writeln!( + out, + " {what:<26} head {:<3} {} positions combine {} blocks {:?} {} {verdict}{}", + p.head.map_or("-".into(), |h| h.to_string()), + p.context, + p.combine_error.map_or("-".into(), |e| format!("{e:.1e}")), + p.blocks, + p.block_error.map_or("-".into(), |e| format!("{e:.1e}")), + p.failure + .as_ref() + .map(|f| format!(" ({})", shown(f))) + .unwrap_or_default() + )?; + } + if let Some(seconds) = attention.rows_seconds { + writeln!(out, " rows opened in {seconds:.2} s")?; + } + if let Some(error) = &attention.rows_error { + writeln!(out, " rows: FAIL ({})", shown(error))?; + } + if let Some(reason) = &attention.rows_unanswered { + writeln!(out, " rows: the node did not answer ({})", shown(reason))?; + } + if let Some(reason) = &attention.rows_missing { + writeln!(out, " rows: cannot check ({})", shown(reason))?; + } + Ok(()) +} diff --git a/crates/skippy-receipt-audit/src/chat_reply.rs b/crates/skippy-receipt-audit/src/chat_reply.rs new file mode 100644 index 00000000..12397941 --- /dev/null +++ b/crates/skippy-receipt-audit/src/chat_reply.rs @@ -0,0 +1,14 @@ +//! The reply a client received for the turn it audits. + +/// What the node answered: its content and reasoning text, and the receipt +/// when the response carried it. +pub struct ChatReply { + /// The model the request named. + pub model: String, + pub content: String, + pub reasoning: String, + /// The node says it stopped at the token limit (`finish_reason` is + /// `length`). Its text may then end before the sampled tokens' text + /// does: inside a character, or before a marker it held back. + pub cut_short: bool, +} diff --git a/crates/skippy-receipt-audit/src/claimed_file.rs b/crates/skippy-receipt-audit/src/claimed_file.rs new file mode 100644 index 00000000..65a72b76 --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file.rs @@ -0,0 +1,308 @@ +//! The claimed GGUF an audit checks against: a local file, or a Hugging +//! Face file named `repo@revision/file` that the audit reads by range into +//! a sparse local copy, so the client never downloads the model. +//! +//! Who named the model decides how it opens: +//! +//! - The user ([`open`]): a file here, or a Hugging Face file at any +//! revision, a branch included. +//! - A node, in a receipt ([`open_named_by_receipt`], [`open_remote`]): +//! a Hugging Face file only, never a file here, and only at a commit. A +//! branch can move, so a node could fail an audit and then publish other +//! bytes under the same name, and nobody could check the failure again. +//! A commit is not enough when the request named a branch: Hugging Face +//! also serves the commits of pull requests, which anyone can open. So +//! the caller asks [`check_on_branch`] whether the commit is in the +//! branch's history before it opens the file (`branch_history`). +//! +//! The name is hostile text when a node wrote it ([`hf_file`]), and the +//! copy's path stays under the cache root whatever it says (`cache_path`). +//! The copy is pinned by the commit Hugging Face resolves the revision to, +//! which [`ClaimedFile::pinned`] returns. The token goes to the resolver +//! only (`hf_remote`). + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use skippy_receipts::shards::shard_files; +use skippy_receipts::sparse_copy::eviction::evict; +use skippy_receipts::sparse_copy::{RemoteIdentity, SparseCopy}; +use skippy_receipts::weights::limits::{AUDIT_FETCH_BUDGET, CannotAudit}; +use skippy_receipts::weights::{ByteSource, LocalFile, WeightFile}; + +mod branch_history; +mod cache_path; +pub mod hf_file; +mod hf_remote; + +pub use branch_history::NotOnBranch; +pub use hf_file::HfFile; +use hf_remote::HfRemote; +pub use hf_remote::NoSuchFile; + +const DEFAULT_ENDPOINT: &str = "https://huggingface.co"; +/// The most bytes the sparse copies under a cache root hold. Opening a copy +/// removes the copies used longest ago past it, except the open ones. +pub const MAX_CACHED_COPY_BYTES: u64 = 8 << 30; + +/// The claimed GGUF, opened. +pub struct ClaimedFile { + /// What the native loader reads: the file, or its sparse copy. + pub path: PathBuf, + pub weights: WeightFile, + /// What names this file and no other: `repo@commit/file`, or a local + /// file's path, size and modification time. + pub identity: String, + /// The Hugging Face file at the commit its revision resolved to, to + /// keep with an audit so a recheck reads the same bytes. `None` for a + /// local file. + pub pinned: Option, +} + +/// Where the sparse copies live, unless the caller names a place: under +/// the user's cache directory. The audit trusts what a copy holds, so it is +/// never under the shared temporary directory, where another local user +/// could plant one: a process with no home or cache directory audits +/// nothing. +pub fn default_cache_root() -> Result { + cache_root_in(skippy_model_hf::user_application_cache_dir()) +} + +fn cache_root_in(user_cache: Option) -> Result { + match user_cache { + Some(dir) => Ok(dir.join("receipts").join("claimed")), + None => Err(CannotAudit::new( + "this process has no home or cache directory to keep the claimed model's copy in, and the shared temporary directory is not trusted with it", + ) + .into()), + } +} + +/// Opens `claimed`, a model the user named: a path when it names a file +/// here, else a Hugging Face file, whose sparse copy lives under +/// `cache_root`. Never for a name out of a receipt: +/// [`open_named_by_receipt`] is for that. +pub fn open(claimed: &Path, cache_root: &Path) -> Result { + if claimed.exists() { + let weights = open_local(claimed)?; + return Ok(ClaimedFile { + path: claimed.to_owned(), + weights, + identity: local_identity(claimed)?, + pinned: None, + }); + } + let text = claimed.to_string_lossy(); + let file = HfFile::parse_checked(&text).with_context(|| { + format!( + "the claimed model {text} is neither a file here nor repo@revision/file on Hugging Face" + ) + })?; + open_hf( + &file, + &endpoint(), + skippy_model_hf::hf_token_override(), + cache_root, + ) +} + +/// Opens the model a receipt names. The node wrote the name, so it is only +/// ever a Hugging Face file at a commit ([`open_remote`]): a name that is a +/// path here opens nothing. +pub fn open_named_by_receipt(model: &str, cache_root: &Path) -> Result { + let file = HfFile::parse_checked(model).with_context(|| { + format!("the receipt names {model:?}, not repo@commit/file on Hugging Face") + })?; + open_remote(&file, cache_root) +} + +/// Opens `file` on Hugging Face (or `HF_ENDPOINT`), never a file here: for +/// a claimed model a node named, which must not choose what this machine +/// reads. The revision must be a commit, which names the same bytes for +/// good. +pub fn open_remote(file: &HfFile, cache_root: &Path) -> Result { + require_pinned(file)?; + open_hf( + file, + &endpoint(), + skippy_model_hf::hf_token_override(), + cache_root, + ) +} + +/// Checks that `file`, which a node named at a commit, is in the history +/// of `branch` on Hugging Face (or `HF_ENDPOINT`), for a request that named +/// that branch (the default branch `main` when it named no revision) and no +/// commit. Hugging Face serves the commits of pull requests too, which +/// anyone can open ([`branch_history`]). A commit that is not is a +/// [`NotOnBranch`] error. A caller checks this before it opens the file +/// ([`open_remote`]), so no byte of a file at such a commit is fetched. +pub fn check_on_branch(file: &HfFile, branch: &str) -> Result<()> { + require_pinned(file)?; + branch_history::check( + file, + branch, + &endpoint(), + skippy_model_hf::hf_token_override().as_deref(), + ) +} + +/// Refuses a name a node wrote whose revision can move. +fn require_pinned(file: &HfFile) -> Result<()> { + file.check() + .with_context(|| format!("{file} names no file on Hugging Face"))?; + if !file.is_pinned() { + return Err(CannotAudit::new(format!( + "the receipt names {file}, and the revision {:?} is not a commit: it can move to other bytes, so the audit could not be checked again. A receipt must name the 40-digit commit", + file.revision + )) + .into()); + } + Ok(()) +} + +/// The Hugging Face endpoint: `HF_ENDPOINT`, when set and not empty. +fn endpoint() -> String { + std::env::var("HF_ENDPOINT") + .ok() + .map(|e| e.trim().trim_end_matches('/').to_owned()) + .filter(|e| !e.is_empty()) + .unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()) +} + +/// Opens the sparse copy of `file` and reads its header; for the first +/// shard of a split GGUF, the copies of every shard, at the commit the +/// first resolves to. +pub fn open_hf( + file: &HfFile, + endpoint: &str, + token: Option, + cache_root: &Path, +) -> Result { + // the shards first: a name of too many is refused before any request + let shard_names = split_shards(&file.file)?; + let (first, pinned) = open_hf_copy(file, endpoint, token.clone(), cache_root)?; + let path = first.path().to_owned(); + let weights = match shard_names { + None => WeightFile::open_with_budget(Box::new(first), AUDIT_FETCH_BUDGET), + Some(names) => { + let mut shards: Vec> = vec![Box::new(first)]; + for name in &names[1..] { + let shard = pinned.sibling(name); + shards.push(Box::new( + open_hf_copy(&shard, endpoint, token.clone(), cache_root)?.0, + )); + } + WeightFile::open_shards_with_budget(shards, AUDIT_FETCH_BUDGET) + } + } + .with_context(|| format!("read the GGUF header of {pinned}"))?; + Ok(ClaimedFile { + path, + weights, + identity: pinned.to_string(), + pinned: Some(pinned), + }) +} + +/// Opens the sparse copy of one file, and the file at the commit the copy +/// is pinned to. +fn open_hf_copy( + file: &HfFile, + endpoint: &str, + token: Option, + cache_root: &Path, +) -> Result<(SparseCopy, HfFile)> { + let mut remote = HfRemote::new(file, endpoint, token)?; + let resolved = remote.resolve()?; + let commit = match resolved.commit { + Some(commit) if file.is_pinned() && commit != file.revision => bail!( + "Hugging Face resolved {}@{} to commit {commit}", + file.repo, + file.revision + ), + Some(commit) => commit, + None if file.is_pinned() => file.revision.clone(), + None => bail!( + "Hugging Face did not say which commit {}@{} is at, so its bytes cannot be pinned; name the commit", + file.repo, + file.revision + ), + }; + let size = match resolved.size { + Some(size) => size, + None => remote.probe_size(&resolved.url)?, + }; + remote.set_url(resolved.url)?; + let pinned = file.at(&commit); + remote.pin(&pinned, endpoint)?; + let path = cache_path::sparse_copy_path(cache_root, &pinned)?; + evict(cache_root, MAX_CACHED_COPY_BYTES, &path).with_context(|| { + format!( + "keep the copies under {} within their size", + cache_root.display() + ) + })?; + let identity = RemoteIdentity { + source: pinned.to_string(), + size, + }; + let copy = SparseCopy::open(&path, identity, Box::new(remote))?; + Ok((copy, pinned)) +} + +/// Reads the header of the GGUF at `path`, a local file or a sparse copy, +/// with every shard of a split one, as strictly as an audit opens it: for +/// a caller about to hand the file to the native loader. The copy must +/// hold the header: nothing is fetched. +pub fn read_header(path: &Path) -> Result { + open_local(path) +} + +/// Reads a local GGUF, with every shard of a split one. +fn open_local(path: &Path) -> Result { + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + let Some(names) = split_shards(name)? else { + return WeightFile::open(Box::new(LocalFile::open(path)?)); + }; + let dir = path.parent().unwrap_or(Path::new(".")); + let shards = names + .iter() + .map(|name| Ok(Box::new(LocalFile::open(&dir.join(name))?) as Box)) + .collect::>>()?; + WeightFile::open_shards(shards) +} + +/// The shard files of the split GGUF `file` names, or `None` for a whole +/// GGUF. A claim names a split by its first shard. +fn split_shards(file: &str) -> Result>> { + let name = file.rsplit('/').next().unwrap_or(file); + match skippy_model_ref::split_gguf_shard_info(name) { + None => Ok(None), + Some(shard) if shard.total == "00001" => Ok(None), + Some(shard) if shard.part != "00001" => { + bail!( + "{file} is shard {} of a split GGUF: claim its first shard", + shard.part + ) + } + Some(_) => shard_files(file), + } +} + +fn local_identity(path: &Path) -> Result { + let canonical = path.canonicalize()?; + let meta = std::fs::metadata(&canonical)?; + let modified = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_nanos()); + Ok(format!("{}:{}:{modified}", canonical.display(), meta.len())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipt-audit/src/claimed_file/branch_history.rs b/crates/skippy-receipt-audit/src/claimed_file/branch_history.rs new file mode 100644 index 00000000..828ff7d0 --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file/branch_history.rs @@ -0,0 +1,266 @@ +//! Whether a commit a node named is in the history of the branch the +//! request named, as Hugging Face (or `HF_ENDPOINT`) lists it. +//! +//! Hugging Face serves a file at any commit of a repo by its id, the +//! commits of an open pull request included, and anyone can open a pull +//! request on a public repo. So a commit id alone does not say the repo's +//! owner published those bytes: a node could open a pull request that +//! replaces the file, serve that, and name the pull request's commit. +//! When the request named a branch, or no revision (the default branch +//! `main`), the commit must be in that branch's history. +//! +//! The history is the commit list of the branch, +//! `GET /api/models/{repo}/commits/{branch}`, newest first, one page of up +//! to [`PAGE_LIMIT`] commits at a time, following the `next` link of each +//! answer for at most [`MAX_PAGES`] pages. The commit list of a pull +//! request's ref holds the commits of its branch too, so only the branch's +//! own list counts. A commit found is kept for the process +//! ([`ACCEPTED`]), so an audit of a model already checked asks nothing. +//! A commit not in a list that ended is not on the branch +//! ([`NotOnBranch`]). A list that did not end within the pages, or did +//! not answer, cannot say: that is no audit. + +use std::collections::HashSet; +use std::fmt; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use reqwest::blocking::Client; +use reqwest::header::{AUTHORIZATION, LINK}; +use serde::Deserialize; +use skippy_receipts::weights::limits::CannotAudit; + +use super::hf_file::{HfFile, is_commit}; +use super::hf_remote::read_at_most; + +/// Commits asked for per page. Hugging Face answers 50 without a limit. +const PAGE_LIMIT: u32 = 1000; +/// Pages read before the check gives up: the newest 4,000 commits of the +/// branch, or 200 when the server keeps its own page of 50. +pub(super) const MAX_PAGES: usize = 4; +/// The largest page read, in bytes. A commit takes about 350 bytes. +const MAX_PAGE_BYTES: u64 = 4 << 20; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +/// Accepted (repo, branch, commit) triples kept for the process; past this +/// the set starts over. +const MAX_ACCEPTED: usize = 4096; + +/// The (repo, branch, commit) triples found so far. A commit stays in the +/// history of a branch unless the owner rewrites it. +static ACCEPTED: Mutex>> = Mutex::new(None); + +/// The commit a node named is not in the history of the branch the request +/// named: what it served is not what was asked for. +#[derive(Debug)] +pub struct NotOnBranch(String); + +impl NotOnBranch { + pub fn new(reason: impl Into) -> Self { + Self(reason.into()) + } + + /// Whether `error` is, or was caused by, this mismatch. + pub fn caused(error: &anyhow::Error) -> bool { + error.chain().any(|cause| cause.is::()) + } +} + +impl fmt::Display for NotOnBranch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for NotOnBranch {} + +#[derive(Deserialize)] +struct Commit { + id: String, +} + +/// Checks that `file`'s revision, a commit, is in the history of `branch` +/// of its repo, on the Hugging Face at `endpoint`. +pub(super) fn check( + file: &HfFile, + branch: &str, + endpoint: &str, + token: Option<&str>, +) -> Result<()> { + if !file.is_pinned() { + bail!("{file} is not at a commit, so no history holds it"); + } + let triple = ( + file.repo.to_ascii_lowercase(), + branch.to_owned(), + file.revision.clone(), + ); + if accepted(&triple) { + return Ok(()); + } + let first = commits_url(endpoint, &file.repo, branch)?; + let mut next = Some(first.clone()); + let mut pages = 0; + while let Some(url) = next { + if pages == MAX_PAGES { + return Err(CannotAudit::new(format!( + "the commit {} is not among the newest {MAX_PAGES} pages of commits of {}@{branch}, and older ones are not read", + file.revision, file.repo + )) + .into()); + } + pages += 1; + let (ids, link) = page(&url, &first, token)?; + if ids.contains(&file.revision) { + accept(triple); + return Ok(()); + } + next = link; + } + Err(NotOnBranch(format!( + "the receipt names {}@{}, a commit that is not in the history of the branch {branch} the request named: Hugging Face serves it, but it may be of a pull request anyone can open", + file.repo, file.revision + )) + .into()) +} + +fn accepted(triple: &(String, String, String)) -> bool { + ACCEPTED + .lock() + .is_ok_and(|set| set.as_ref().is_some_and(|set| set.contains(triple))) +} + +fn accept(triple: (String, String, String)) { + if let Ok(mut set) = ACCEPTED.lock() { + let set = set.get_or_insert_with(HashSet::new); + if set.len() >= MAX_ACCEPTED { + set.clear(); + } + set.insert(triple); + } +} + +/// The first page of the commit list of `branch` of `repo`, each part of +/// the name a path segment of its own. +pub(super) fn commits_url(endpoint: &str, repo: &str, branch: &str) -> Result { + let mut url = reqwest::Url::parse(endpoint) + .with_context(|| format!("read the Hugging Face endpoint {endpoint}"))?; + if !matches!(url.scheme(), "http" | "https") { + bail!("the Hugging Face endpoint {endpoint} is not http or https"); + } + let (owner, name) = repo.split_once('/').context("the repo is not owner/name")?; + if branch.is_empty() { + bail!("the branch is empty"); + } + url.path_segments_mut() + .map_err(|()| anyhow::anyhow!("the Hugging Face endpoint {endpoint} holds no path"))? + .pop_if_empty() + .extend(["api", "models", owner, name, "commits", branch]); + url.set_query(Some(&format!("limit={PAGE_LIMIT}"))); + url.set_fragment(None); + Ok(url) +} + +fn client() -> Result { + static CLIENT: OnceLock = OnceLock::new(); + if let Some(client) = CLIENT.get() { + return Ok(client.clone()); + } + let built = Client::builder() + .timeout(REQUEST_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build()?; + Ok(CLIENT.get_or_init(|| built).clone()) +} + +/// The commit ids of one page, and the next page's URL. The next page must +/// be at the origin of the first, which may see the token. +fn page( + url: &reqwest::Url, + first: &reqwest::Url, + token: Option<&str>, +) -> Result<(Vec, Option)> { + let mut request = client()?.get(url.clone()); + if let Some(token) = token { + request = request.header(AUTHORIZATION, format!("Bearer {token}")); + } + let response = request + .send() + .with_context(|| format!("list the commits at {url}"))?; + let status = response.status(); + if !status.is_success() { + return Err(CannotAudit::new(format!( + "Hugging Face answered {status} for the commit list {url}" + )) + .into()); + } + let link = response + .headers() + .get(LINK) + .and_then(|v| v.to_str().ok()) + .and_then(next_link) + .map(|next| url.join(&next)) + .transpose()?; + if let Some(next) = &link + && next.origin() != first.origin() + { + bail!("the commit list {url} links to {next}, at another origin"); + } + let body = read_at_most(response, MAX_PAGE_BYTES) + .with_context(|| format!("read the commit list {url}"))?; + let commits: Vec = + serde_json::from_slice(&body).with_context(|| format!("decode the commit list {url}"))?; + let ids = commits + .into_iter() + .map(|commit| commit.id) + .filter(|id| is_commit(id)) + .collect(); + Ok((ids, link)) +} + +/// The target of the `rel="next"` link of a `Link` header. +fn next_link(header: &str) -> Option { + header.split(',').find_map(|part| { + let (target, params) = part.split_once(';')?; + let next = params + .split(';') + .any(|p| matches!(p.trim(), "rel=\"next\"" | "rel=next")); + let target = target.trim().strip_prefix('<')?.strip_suffix('>')?; + next.then(|| target.to_owned()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_commit_list_url_holds_each_part_as_a_segment() { + let url = commits_url("https://huggingface.co", "o/m", "main").unwrap(); + assert_eq!( + url.as_str(), + "https://huggingface.co/api/models/o/m/commits/main?limit=1000" + ); + // a ref with slashes stays one segment + let url = commits_url("http://mirror.test/hf/", "o/m", "refs/pr/1").unwrap(); + assert_eq!( + url.as_str(), + "http://mirror.test/hf/api/models/o/m/commits/refs%2Fpr%2F1?limit=1000" + ); + assert!(commits_url("ftp://mirror.test", "o/m", "main").is_err()); + assert!(commits_url("https://huggingface.co", "o/m", "").is_err()); + } + + #[test] + fn only_the_next_link_is_followed() { + let header = "; rel=\"next\""; + assert_eq!( + next_link(header).as_deref(), + Some("https://h.test/api/models/o/m/commits/main?p=1&limit=50") + ); + let both = "; rel=\"prev\", ; rel=\"next\""; + assert_eq!(next_link(both).as_deref(), Some("https://h.test/a?p=2")); + assert_eq!(next_link("; rel=\"prev\""), None); + assert_eq!(next_link("garbage"), None); + } +} diff --git a/crates/skippy-receipt-audit/src/claimed_file/cache_path.rs b/crates/skippy-receipt-audit/src/claimed_file/cache_path.rs new file mode 100644 index 00000000..f91086d5 --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file/cache_path.rs @@ -0,0 +1,232 @@ +//! Where the sparse copy of a claimed file lives: under the cache root, and +//! nowhere else. +//! +//! The path is `root/owner--name/commit/path/to/file.gguf`, built one +//! component at a time from a checked name. `Path::join` with an absolute +//! path or a `..` would leave the root, so nothing is joined that is not a +//! single plain component, and the result is checked again: it is under the +//! root as written, no component below the root is a symlink, and what +//! exists of it resolves to a place under the root. + +use std::path::{Component, Path, PathBuf}; + +use anyhow::{Context, Result, bail}; + +use super::hf_file::HfFile; + +/// The path of the sparse copy of `pinned`, a file at a commit, under +/// `cache_root`, which is created. +pub(super) fn sparse_copy_path(cache_root: &Path, pinned: &HfFile) -> Result { + pinned + .check() + .with_context(|| format!("{pinned} names no path in the cache"))?; + if !pinned.is_pinned() { + bail!( + "the cache holds files by commit, and {} is not one", + pinned.revision + ); + } + std::fs::create_dir_all(cache_root) + .with_context(|| format!("create {}", cache_root.display()))?; + // the root may be a symlink: what is under it may not + let root = cache_root + .canonicalize() + .with_context(|| format!("resolve {}", cache_root.display()))?; + let mut parts = vec![pinned.repo.replace('/', "--"), pinned.revision.clone()]; + parts.extend(pinned.file.split('/').map(str::to_owned)); + let mut path = cache_root.to_owned(); + let mut resolved = root.clone(); + for part in &parts { + if !is_plain_component(part) { + bail!("{part:?} is not a name of one file or directory"); + } + path.push(part); + resolved.push(part); + refuse_symlink(&resolved)?; + } + let inside = resolved + .strip_prefix(&root) + .is_ok_and(|rest| rest.components().count() == parts.len()); + if !inside { + bail!( + "the sparse copy of {pinned} would be outside {}", + cache_root.display() + ); + } + // what exists of the path, resolved by the system, is under the root + let existing = resolved + .ancestors() + .find(|ancestor| ancestor.exists()) + .unwrap_or(&root); + let real = existing + .canonicalize() + .with_context(|| format!("resolve {}", existing.display()))?; + if !real.starts_with(&root) { + bail!( + "{} resolves to {}, outside {}", + existing.display(), + real.display(), + root.display() + ); + } + Ok(path) +} + +/// Whether `part` is one normal component of a path: no separator, no +/// prefix or root, and not `.` or `..`. +fn is_plain_component(part: &str) -> bool { + let mut components = Path::new(part).components(); + matches!( + (components.next(), components.next()), + (Some(Component::Normal(name)), None) if name == part + ) +} + +/// Refuses `path` when it is a symlink: a directory of the cache that +/// leads elsewhere, or a file that is another. +fn refuse_symlink(path: &Path) -> Result<()> { + match std::fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() => bail!( + "{} is a symlink: the cache of claimed models holds none", + path.display() + ), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error).with_context(|| format!("inspect {}", path.display())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + + fn pinned(file: &str) -> HfFile { + HfFile { + repo: "owner/model".into(), + revision: COMMIT.into(), + file: file.into(), + } + } + + #[test] + fn the_copy_is_under_the_root_by_repo_commit_and_file() { + let cache = tempfile::tempdir().unwrap(); + let root = cache.path().join("receipts").join("claimed"); + let path = sparse_copy_path(&root, &pinned("sub/model.gguf")).unwrap(); + assert_eq!( + path, + root.join("owner--model") + .join(COMMIT) + .join("sub") + .join("model.gguf") + ); + assert!(root.is_dir()); + // nothing below the root is made to name the path + assert!(!root.join("owner--model").exists()); + } + + #[test] + fn a_name_that_leaves_the_root_has_no_path() { + let cache = tempfile::tempdir().unwrap(); + let outside = cache.path().join("outside.gguf"); + let absolute = outside.to_str().unwrap().to_owned(); + for file in [ + absolute.as_str(), + "/etc/x.gguf", + "../x.gguf", + "a/../../../x.gguf", + "..", + "a//x.gguf", + "a/./x.gguf", + "a\\..\\x.gguf", + "C:/x.gguf", + "C:x.gguf", + "", + ] { + let refused = sparse_copy_path(&cache.path().join("root"), &pinned(file)); + assert!(refused.is_err(), "{file:?} has the path {refused:?}"); + } + for (repo, revision) in [ + ("owner/model", "main"), + ("owner/model", ".."), + ("owner/model", "../../../../etc"), + ("../model", COMMIT), + ("owner/..", COMMIT), + ("/abs/model", COMMIT), + ("owner", COMMIT), + ] { + let name = HfFile { + repo: repo.into(), + revision: revision.into(), + file: "x.gguf".into(), + }; + let refused = sparse_copy_path(&cache.path().join("root"), &name); + assert!(refused.is_err(), "{name} has the path {refused:?}"); + } + assert!(!outside.exists()); + } + + #[test] + fn only_one_plain_component_is_joined() { + for part in ["x.gguf", "owner--model", COMMIT] { + assert!(is_plain_component(part), "{part}"); + } + for part in ["", ".", "..", "/", "/x", "a/b", "a/", "./a"] { + assert!(!is_plain_component(part), "{part:?}"); + } + } + + #[cfg(unix)] + #[test] + fn a_symlink_below_the_root_is_refused() { + use std::os::unix::fs::symlink; + let cache = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + let root = cache.path().join("root"); + let name = pinned("sub/model.gguf"); + // the repo's directory leads out of the cache + std::fs::create_dir_all(&root).unwrap(); + symlink(elsewhere.path(), root.join("owner--model")).unwrap(); + let refused = sparse_copy_path(&root, &name).unwrap_err().to_string(); + assert!(refused.contains("symlink"), "{refused}"); + std::fs::remove_file(root.join("owner--model")).unwrap(); + // a directory deeper down does + let commit = root.join("owner--model").join(COMMIT); + std::fs::create_dir_all(&commit).unwrap(); + symlink(elsewhere.path(), commit.join("sub")).unwrap(); + assert!(sparse_copy_path(&root, &name).is_err()); + std::fs::remove_file(commit.join("sub")).unwrap(); + // the file itself is a link to another, here or not yet anywhere + std::fs::create_dir_all(commit.join("sub")).unwrap(); + let target = elsewhere.path().join("victim"); + symlink(&target, commit.join("sub").join("model.gguf")).unwrap(); + assert!(sparse_copy_path(&root, &name).is_err()); + std::fs::write(&target, b"kept").unwrap(); + assert!(sparse_copy_path(&root, &name).is_err()); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + std::fs::remove_file(commit.join("sub").join("model.gguf")).unwrap(); + // a link inside the cache to a place inside it is one too + symlink(commit.join("sub"), commit.join("other")).unwrap(); + assert!(sparse_copy_path(&root, &pinned("other/model.gguf")).is_err()); + assert!(sparse_copy_path(&root, &name).is_ok()); + assert!(std::fs::read_dir(elsewhere.path()).unwrap().count() == 1); + } + + #[cfg(unix)] + #[test] + fn a_root_that_is_a_symlink_still_holds_copies() { + use std::os::unix::fs::symlink; + let cache = tempfile::tempdir().unwrap(); + let real = cache.path().join("real"); + std::fs::create_dir_all(&real).unwrap(); + let root = cache.path().join("root"); + symlink(&real, &root).unwrap(); + let path = sparse_copy_path(&root, &pinned("model.gguf")).unwrap(); + assert_eq!( + path, + root.join("owner--model").join(COMMIT).join("model.gguf") + ); + } +} diff --git a/crates/skippy-receipt-audit/src/claimed_file/hf_file.rs b/crates/skippy-receipt-audit/src/claimed_file/hf_file.rs new file mode 100644 index 00000000..7c8c8782 --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file/hf_file.rs @@ -0,0 +1,342 @@ +//! The name of a claimed GGUF on Hugging Face, +//! `owner/name@revision/path/to/file.gguf`. +//! +//! The node that issued a receipt writes this name, and the client turns it +//! into a URL and into a path under its cache. So the name is checked as +//! hostile text: each part holds only characters that mean the same in a +//! URL, in a path on any platform and in a file name, and no part is one a +//! path or a URL would resolve away. What is not plainly a repo, a revision +//! and a GGUF file is refused. + +use std::fmt; + +use anyhow::{Context, Result, bail}; + +/// The longest name, in bytes. +const MAX_NAME_BYTES: usize = 1024; +/// The longest owner or repo name, as Hugging Face has it. +const MAX_REPO_PART_BYTES: usize = 96; +const MAX_REVISION_BYTES: usize = 128; +/// The longest component of the file's path: the limit of common file +/// systems. +const MAX_FILE_PART_BYTES: usize = 255; +/// The most components of the file's path. +const MAX_FILE_PARTS: usize = 16; +/// The file is a GGUF. The copy's record and lock sit next to it under +/// other suffixes, which a claimed file therefore never has. +const FILE_SUFFIX: &str = ".gguf"; +/// Names Windows gives to devices, with any extension. +const DEVICE_NAMES: [&str; 4] = ["con", "prn", "aux", "nul"]; + +/// A file of a Hugging Face model repo at a revision. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HfFile { + pub repo: String, + pub revision: String, + pub file: String, +} + +impl HfFile { + /// Parses `owner/name@revision/path/to/file.gguf`, or `None` when the + /// text is not such a name ([`Self::parse_checked`] says why). + pub fn parse(text: &str) -> Option { + Self::parse_checked(text).ok() + } + + /// Parses `owner/name@revision/path/to/file.gguf` strictly. + pub fn parse_checked(text: &str) -> Result { + if text.len() > MAX_NAME_BYTES { + bail!("a model name of {} bytes is too long", text.len()); + } + let (repo, rest) = text + .split_once('@') + .context("it is not repo@revision/file")?; + let (revision, file) = rest + .split_once('/') + .context("it names no file after the revision")?; + let parsed = Self { + repo: repo.to_owned(), + revision: revision.to_owned(), + file: file.to_owned(), + }; + parsed.check()?; + Ok(parsed) + } + + /// Checks every part, as [`Self::parse_checked`] does: the fields are + /// public, so a name built from them is checked again before it is a + /// URL or a path. + pub fn check(&self) -> Result<()> { + let (owner, name) = self + .repo + .split_once('/') + .context("the repo is not owner/name")?; + for (part, what) in [(owner, "the repo's owner"), (name, "the repo's name")] { + check_word(part, what, MAX_REPO_PART_BYTES, "")?; + // the cache joins owner and name with `--` + if part.contains("--") { + bail!("{what} {part:?} holds `--`"); + } + } + check_word(&self.revision, "the revision", MAX_REVISION_BYTES, "")?; + let parts: Vec<&str> = self.file.split('/').collect(); + if parts.len() > MAX_FILE_PARTS { + bail!("the file's path has more than {MAX_FILE_PARTS} parts"); + } + for part in &parts { + check_word( + part, + "a part of the file's path", + MAX_FILE_PART_BYTES, + "+=,", + )?; + let stem = part.split('.').next().unwrap_or(part).to_ascii_lowercase(); + if is_device_name(&stem) { + bail!("a part of the file's path, {part:?}, names a device"); + } + } + match parts.last() { + Some(last) if last.len() > FILE_SUFFIX.len() && last.ends_with(FILE_SUFFIX) => Ok(()), + _ => bail!("the file {:?} is not a {FILE_SUFFIX} file", self.file), + } + } + + /// Whether the revision is a commit, which names the same bytes + /// forever: 40 lowercase hex digits. A branch or a tag can move. + pub fn is_pinned(&self) -> bool { + is_commit(&self.revision) + } + + /// The same file at `revision`. + pub fn at(&self, revision: &str) -> Self { + Self { + repo: self.repo.clone(), + revision: revision.to_owned(), + file: self.file.clone(), + } + } + + /// The same repo and revision's `file`. + pub fn sibling(&self, file: &str) -> Self { + Self { + repo: self.repo.clone(), + revision: self.revision.clone(), + file: file.to_owned(), + } + } +} + +impl fmt::Display for HfFile { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}@{}/{}", self.repo, self.revision, self.file) + } +} + +/// Whether `text` is a commit id: 40 lowercase hex digits. +pub fn is_commit(text: &str) -> bool { + text.len() == 40 + && text + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// Checks one part of a name: ASCII letters and digits, `-`, `_`, `.` and +/// the characters of `also`; not empty, at most `max` bytes, no `..`, no +/// leading `.` or `-`, no trailing `.`. So it holds no separator of a path +/// or a URL (`/`, `\`, `:`, `?`, `#`, `%`, `@`), no control character and +/// no space, and is no `.` or `..`. +fn check_word(part: &str, what: &str, max: usize, also: &str) -> Result<()> { + if part.is_empty() { + bail!("{what} is empty"); + } + if part.len() > max { + bail!("{what} is longer than {max} bytes"); + } + let allowed = |c: char| c.is_ascii_alphanumeric() || "-_.".contains(c) || also.contains(c); + if let Some(c) = part.chars().find(|&c| !allowed(c)) { + bail!("{what} {part:?} holds {c:?}"); + } + if part.contains("..") || part.starts_with(['.', '-']) || part.ends_with('.') { + bail!("{what} {part:?} starts with `.` or `-`, ends with `.` or holds `..`"); + } + Ok(()) +} + +/// Whether `stem`, in lowercase, is a device on Windows: `con`, `nul`, +/// `com1`, `lpt9` and their like. +fn is_device_name(stem: &str) -> bool { + let numbered = |prefix: &str| { + stem.strip_prefix(prefix) + .is_some_and(|n| n.len() == 1 && n.bytes().all(|b| b.is_ascii_digit())) + }; + DEVICE_NAMES.contains(&stem) || numbered("com") || numbered("lpt") +} + +#[cfg(test)] +mod tests { + use super::*; + + const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + + #[test] + fn references_parse_as_repo_revision_and_file() { + assert_eq!( + HfFile::parse("unsloth/Qwen3-4B-GGUF@main/Q8_0/Qwen3-4B-Q8_0.gguf"), + Some(HfFile { + repo: "unsloth/Qwen3-4B-GGUF".into(), + revision: "main".into(), + file: "Q8_0/Qwen3-4B-Q8_0.gguf".into(), + }) + ); + for name in [ + "TheBloke/Mistral-7B-Instruct-v0.2-GGUF@main/mistral-7b-instruct-v0.2.Q4_K_M.gguf", + "o/m@v1.0/a/b/c/M-00001-of-00003.gguf", + "o_1/m.x@0123456789abcdef0123456789abcdef01234567/m+lora=1,2.gguf", + ] { + let parsed = HfFile::parse_checked(name).unwrap(); + assert_eq!(parsed.to_string(), name); + } + assert_eq!(HfFile::parse("Qwen3-4B-Q8_0.gguf"), None); + assert_eq!(HfFile::parse("owner/model@main"), None); + assert_eq!(HfFile::parse("owner/model@main/../x.gguf"), None); + assert_eq!(HfFile::parse("model@main/x.gguf"), None); + } + + #[test] + fn only_a_commit_is_pinned() { + let pinned = |revision: &str| { + HfFile::parse(&format!("o/m@{revision}/x.gguf")) + .unwrap() + .is_pinned() + }; + assert!(pinned(COMMIT)); + assert!(!pinned("main")); + assert!(!pinned(&COMMIT[..39])); + assert!(!pinned(&format!("{COMMIT}0"))); + assert!(!pinned(&COMMIT.to_uppercase())); + assert!(!pinned(&COMMIT.replace('0', "g"))); + let at = HfFile::parse("o/m@main/x.gguf").unwrap().at(COMMIT); + assert!(at.is_pinned()); + assert_eq!(at.to_string(), format!("o/m@{COMMIT}/x.gguf")); + } + + /// Names a node may write to reach outside the repo, the cache or the + /// resolver. None is a file of a repo. + #[test] + fn names_that_are_not_a_file_of_a_repo_are_refused() { + let long = "a".repeat(300); + let cases = [ + // absolute paths, with the doubled slash Hugging Face serves + "evil/m@main//home/u/.ssh/authorized_keys", + "evil/m@main//etc/cron.d/x.gguf", + "evil/m@main//x.gguf", + "evil/m@main/a//x.gguf", + "evil/m@main/a/x.gguf/", + "evil/m@main/", + // `..` and `.` in every part + "../m@main/x.gguf", + "evil/..@main/x.gguf", + "evil/m@../x.gguf", + "evil/m@main/../x.gguf", + "evil/m@main/a/../../x.gguf", + "evil/m@main/a/..x.gguf", + "evil/m@main/a..b/x.gguf", + "evil/m@main/./x.gguf", + "./m@main/x.gguf", + "evil/.@main/x.gguf", + "evil/m@./x.gguf", + "evil/.m@main/x.gguf", + "evil/m@main/.hidden/x.gguf", + "evil/m@main/x.gguf.", + // backslashes and drive letters + "evil/m@main/..\\..\\x.gguf", + "evil/m@main/a\\x.gguf", + "evil\\m/m@main/x.gguf", + "evil/m@main/C:/x.gguf", + "evil/m@main/C:x.gguf", + "evil/m@C:/x.gguf", + "C:/m@main/x.gguf", + "evil/m@main/x.gguf:stream", + // what a URL reads as something else + "evil/m@main/x.gguf?download=1", + "evil/m@main/x.gguf#frag", + "evil/m@main/%2e%2e/x.gguf", + "evil/m@main/a%2fb.gguf", + "evil/m@main?x/x.gguf", + "evil/m@main#x/x.gguf", + "evil/m@ma%69n/x.gguf", + "evil/m@main@other/x.gguf", + "evil/m?x@main/x.gguf", + "evil%2f/m@main/x.gguf", + "http://evil/m@main/x.gguf", + "evil/m@main/x y.gguf", + "evil/m@main/x.gguf ", + " evil/m@main/x.gguf", + // control characters + "evil/m@main/x\n.gguf", + "evil/m@main/x\0.gguf", + "evil/m@main/x\r\nHost: other.gguf", + "evil/m@ma\tin/x.gguf", + "evil/m\u{7f}@main/x.gguf", + // not ASCII + "evil/m@main/x\u{202e}.gguf", + "evil/m@main/x.gguf", + // empty parts and parts in the wrong number + "/m@main/x.gguf", + "evil/@main/x.gguf", + "evil/m@/x.gguf", + "evil/m/extra@main/x.gguf", + "@main/x.gguf", + "evil/m@main", + "", + // names the cache would confuse with another repo or an option + "a--b/c@main/x.gguf", + "a/b--c@main/x.gguf", + "-rf/m@main/x.gguf", + "evil/m@-main/x.gguf", + "evil/m@main/-x.gguf", + // not a GGUF: the copy's own files, and files of no model + "evil/m@main/x.gguf.ranges", + "evil/m@main/x.gguf.lock", + "evil/m@main/x.bin", + "evil/m@main/.gguf", + "evil/m@main/x.GGUF", + "evil/m@main/gguf", + // devices on Windows + "evil/m@main/NUL.gguf", + "evil/m@main/con/x.gguf", + "evil/m@main/COM1.x.gguf", + "evil/m@main/a/lpt9.gguf", + ]; + for name in cases { + let refused = HfFile::parse_checked(name); + assert!(refused.is_err(), "{name:?} parsed as {refused:?}"); + assert_eq!(HfFile::parse(name), None); + } + // overlong names and parts + for name in [ + format!("{long}/m@main/x.gguf"), + format!("evil/{long}@main/x.gguf"), + format!("evil/m@{long}/x.gguf"), + format!("evil/m@main/{long}.gguf"), + format!("evil/m@main/{}x.gguf", "a/".repeat(MAX_FILE_PARTS)), + format!("evil/m@main/{}x.gguf", "abcdefgh/".repeat(200)), + ] { + assert!(HfFile::parse_checked(&name).is_err(), "{name:?}"); + } + assert!(HfFile::parse_checked(&format!("evil/m@main/{}x.gguf", "a/".repeat(15))).is_ok()); + } + + #[test] + fn a_name_built_from_its_fields_is_checked_too() { + let good = HfFile::parse("o/m@main/x.gguf").unwrap(); + assert!(good.check().is_ok()); + assert!(good.sibling("/etc/passwd").check().is_err()); + assert!(good.sibling("../x.gguf").check().is_err()); + assert!(good.at("../../main").check().is_err()); + assert!(good.at("").check().is_err()); + let mut repo = good.clone(); + repo.repo = "o/m/../../x".into(); + assert!(repo.check().is_err()); + } +} diff --git a/crates/skippy-receipt-audit/src/claimed_file/hf_remote.rs b/crates/skippy-receipt-audit/src/claimed_file/hf_remote.rs new file mode 100644 index 00000000..29bc689b --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file/hf_remote.rs @@ -0,0 +1,450 @@ +//! A claimed file on Hugging Face (or `HF_ENDPOINT`), read by range. +//! +//! The resolver names the commit a revision is at and redirects to a +//! signed CDN URL, which the range requests reuse until it expires. The +//! token goes to the resolver's origin only: the redirects of a resolve are +//! read, not followed, and a range request carries the token only to that +//! origin. An `https` resolver is never left for `http`. With a plain +//! `http://` endpoint nothing protects the bytes in transit. + +use std::io::Read; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use reqwest::StatusCode; +use reqwest::blocking::Client; +use reqwest::header::{AUTHORIZATION, CONTENT_RANGE, HeaderMap, LOCATION, RANGE}; +use skippy_receipts::sparse_copy::RangeFetch; + +use super::hf_file::{HfFile, is_commit}; + +/// Hugging Face has no file of the name at the revision asked for. A node +/// that names a commit of the right repo that does not hold the file it +/// claims to serve names nothing that can be checked. +#[derive(Debug)] +pub struct NoSuchFile(String); + +impl NoSuchFile { + pub fn new(reason: impl Into) -> Self { + Self(reason.into()) + } + + /// Whether `error` is, or was caused by, a file that is not there. + pub fn caused(error: &anyhow::Error) -> bool { + error.chain().any(|cause| cause.is::()) + } +} + +impl std::fmt::Display for NoSuchFile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for NoSuchFile {} + +/// Redirects the resolver may send before it names the file's URL, and the +/// file's server after. +const MAX_REDIRECTS: usize = 5; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); + +/// The HTTP clients of every claimed file of the process, so the files of +/// a model and the shards of a split share connections. +#[derive(Clone)] +struct Clients { + /// For the resolver: redirects are read, not followed. + resolve: Client, + /// For the file's bytes. + fetch: Client, +} + +impl Clients { + fn shared() -> Result { + static SHARED: OnceLock = OnceLock::new(); + if let Some(clients) = SHARED.get() { + return Ok(clients.clone()); + } + let built = Self { + resolve: Client::builder() + .timeout(REQUEST_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build()?, + fetch: Client::builder() + .timeout(REQUEST_TIMEOUT) + .redirect(reqwest::redirect::Policy::custom(follow_redirect)) + .build()?, + }; + Ok(SHARED.get_or_init(|| built).clone()) + } +} + +/// Follows a redirect of the file's server, a few times and never from +/// `https` to `http`. The client drops the token when a redirect leaves the +/// origin. +fn follow_redirect(attempt: reqwest::redirect::Attempt<'_>) -> reqwest::redirect::Action { + let previous = attempt.previous(); + if previous.len() > MAX_REDIRECTS { + return attempt.error("the file's server redirected too many times"); + } + let was_https = previous.last().is_some_and(|url| url.scheme() == "https"); + if was_https && attempt.url().scheme() != "https" { + return attempt.error("the file's server redirected from https to http"); + } + attempt.follow() +} + +pub(super) struct HfRemote { + /// The resolver of the file at its revision, and once the copy is + /// pinned ([`Self::pin`]), at the commit the copy holds. + resolver: reqwest::Url, + token: Option, + clients: Clients, + /// The file's URL, resolved once and again when it expires. + url: Mutex>, +} + +/// What the resolver said of the file. +pub(super) struct Resolved { + pub(super) url: reqwest::Url, + pub(super) size: Option, + /// The commit the revision is at. + pub(super) commit: Option, +} + +/// The resolver's URL of `file`, each part of the name a path segment of +/// its own: a part can add no segment, query or fragment. +pub(super) fn resolve_url(endpoint: &str, file: &HfFile) -> Result { + file.check() + .with_context(|| format!("{file} names no file on Hugging Face"))?; + let mut url = reqwest::Url::parse(endpoint) + .with_context(|| format!("read the Hugging Face endpoint {endpoint}"))?; + if !matches!(url.scheme(), "http" | "https") { + bail!("the Hugging Face endpoint {endpoint} is not http or https"); + } + let (owner, name) = file + .repo + .split_once('/') + .context("the repo is not owner/name")?; + url.path_segments_mut() + .map_err(|()| anyhow::anyhow!("the Hugging Face endpoint {endpoint} holds no path"))? + .pop_if_empty() + .extend([owner, name, "resolve", file.revision.as_str()]) + .extend(file.file.split('/')); + url.set_query(None); + url.set_fragment(None); + Ok(url) +} + +impl HfRemote { + pub(super) fn new(file: &HfFile, endpoint: &str, token: Option) -> Result { + Ok(Self { + resolver: resolve_url(endpoint, file)?, + token, + clients: Clients::shared()?, + url: Mutex::new(None), + }) + } + + /// Resolves the file at `pinned`, the commit its sparse copy is keyed + /// by, from now on. A branch can move while the copy is open: a range + /// request resolved again after its URL expires must never take the + /// bytes of another commit into this copy. + pub(super) fn pin(&mut self, pinned: &HfFile, endpoint: &str) -> Result<()> { + self.resolver = resolve_url(endpoint, pinned)?; + Ok(()) + } + + /// Follows the resolver's redirects on its own origin and stops at the + /// first URL elsewhere, the CDN's, or at the file. + pub(super) fn resolve(&self) -> Result { + let mut url = self.resolver.clone(); + let mut size = None; + let mut commit = None; + for _ in 0..=MAX_REDIRECTS { + let mut request = self.clients.resolve.head(url.clone()); + if let Some(token) = &self.token { + request = request.header(AUTHORIZATION, format!("Bearer {token}")); + } + let response = request + .send() + .with_context(|| format!("reach Hugging Face at {url}"))?; + let headers = response.headers(); + size = size.or_else(|| header_u64(headers, "x-linked-size")); + if commit.is_none() { + commit = commit_header(headers)?; + } + let status = response.status(); + if status.is_success() { + size = size.or_else(|| response.content_length().filter(|&n| n > 0)); + return Ok(Resolved { url, size, commit }); + } + if status == StatusCode::NOT_FOUND { + return Err(anyhow::Error::new(NoSuchFile::new(format!( + "Hugging Face has no such file: it answered {status} for {url}" + )))); + } + if !status.is_redirection() { + bail!("Hugging Face answered {status} for {url}"); + } + let location = header_str(headers, LOCATION.as_str()) + .with_context(|| format!("Hugging Face redirected {url} nowhere"))?; + let next = url.join(&location)?; + if !matches!(next.scheme(), "http" | "https") + || (url.scheme() == "https" && next.scheme() != "https") + { + bail!("Hugging Face redirected {url} to {next}, which is not as safe"); + } + if !self.is_resolver(&next) { + return Ok(Resolved { + url: next, + size, + commit, + }); + } + url = next; + } + bail!("Hugging Face redirected {} too many times", self.resolver) + } + + /// Whether `url` is at the resolver's origin (scheme, host and port), + /// which may see the token. + fn is_resolver(&self, url: &reqwest::Url) -> bool { + url.origin() == self.resolver.origin() + } + + /// The file's size from a one-byte range request. + pub(super) fn probe_size(&self, url: &reqwest::Url) -> Result { + let response = self.range_request(url, 0, 1)?; + let range = header_str(response.headers(), CONTENT_RANGE.as_str()) + .context("the file's server sent no Content-Range")?; + range + .rsplit_once('/') + .and_then(|(_, total)| total.parse().ok()) + .with_context(|| format!("unreadable Content-Range {range}")) + } + + /// Keeps `url` as the file's, for the range requests. + pub(super) fn set_url(&self, url: reqwest::Url) -> Result<()> { + *self + .url + .lock() + .map_err(|_| anyhow::anyhow!("url lock poisoned"))? = Some(url); + Ok(()) + } + + fn range_request( + &self, + url: &reqwest::Url, + offset: u64, + len: u64, + ) -> Result { + let last = len + .checked_sub(1) + .and_then(|n| offset.checked_add(n)) + .context("a range request of no bytes, or past any offset")?; + let mut request = self + .clients + .fetch + .get(url.clone()) + .header(RANGE, format!("bytes={offset}-{last}")); + if self.is_resolver(url) + && let Some(token) = &self.token + { + request = request.header(AUTHORIZATION, format!("Bearer {token}")); + } + let response = request.send()?; + match response.status() { + StatusCode::PARTIAL_CONTENT => Ok(response), + status => bail!("a range request answered {status}, not 206"), + } + } + + fn current_url(&self) -> Result { + let mut url = self + .url + .lock() + .map_err(|_| anyhow::anyhow!("url lock poisoned"))?; + match &*url { + Some(url) => Ok(url.clone()), + None => { + let resolved = self.resolve()?.url; + *url = Some(resolved.clone()); + Ok(resolved) + } + } + } + + /// Reads `len` bytes at `offset`: the answer must say it holds those + /// bytes, and no more than `len` of its body is read. + fn fetch_from(&self, url: &reqwest::Url, offset: u64, len: u64) -> Result> { + let response = self.range_request(url, offset, len)?; + let range = header_str(response.headers(), CONTENT_RANGE.as_str()) + .context("a range request was answered with no Content-Range")?; + check_content_range(&range, offset, len)?; + let bytes = read_at_most(response, len)?; + if bytes.len() as u64 != len { + bail!("a range request sent {} bytes, not {len}", bytes.len()); + } + Ok(bytes) + } +} + +/// Checks that `range`, a `Content-Range` header, names the `len` bytes at +/// `offset`. +fn check_content_range(range: &str, offset: u64, len: u64) -> Result<()> { + let span = range + .strip_prefix("bytes ") + .and_then(|rest| rest.split_once('/')) + .and_then(|(span, _)| span.split_once('-')) + .and_then(|(first, last)| Some((first.parse::().ok()?, last.parse::().ok()?))); + let last = offset.checked_add(len).and_then(|end| end.checked_sub(1)); + match (span, last) { + (Some((first, sent_last)), Some(last)) if first == offset && sent_last == last => Ok(()), + _ => { + bail!("a range request for {len} bytes at {offset} was answered with the range {range}") + } + } +} + +/// The body of `response`, refused past `max` bytes: no more than `max + 1` +/// bytes are read, whatever the server sends. +pub(super) fn read_at_most(response: reqwest::blocking::Response, max: u64) -> Result> { + if let Some(declared) = response.content_length() + && declared > max + { + bail!("an answer of {declared} bytes is longer than the {max} asked for"); + } + let mut body = Vec::new(); + response + .take(max.saturating_add(1)) + .read_to_end(&mut body) + .context("read an answer")?; + if body.len() as u64 > max { + bail!("an answer is longer than the {max} bytes asked for"); + } + Ok(body) +} + +impl RangeFetch for HfRemote { + fn fetch(&self, offset: u64, len: u64) -> Result> { + let url = self.current_url()?; + match self.fetch_from(&url, offset, len) { + Ok(bytes) => Ok(bytes), + Err(first) => { + // a signed URL expires after about an hour: resolve it again + let fresh = self.resolve().context(first)?.url; + if let Ok(mut url) = self.url.lock() { + *url = Some(fresh.clone()); + } + self.fetch_from(&fresh, offset, len) + } + } + } +} + +/// The commit the resolver says the revision is at. It becomes a directory +/// of the cache and the pin of the copy, so anything but a commit id is an +/// error. +fn commit_header(headers: &HeaderMap) -> Result> { + match header_str(headers, "x-repo-commit") { + Some(commit) if is_commit(&commit) => Ok(Some(commit)), + Some(other) => bail!("Hugging Face named the commit {other:?}, which is not a commit"), + None => Ok(None), + } +} + +fn header_str(headers: &HeaderMap, name: &str) -> Option { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(|v| v.trim_matches('"').to_owned()) + .filter(|v| !v.is_empty()) +} + +fn header_u64(headers: &HeaderMap, name: &str) -> Option { + header_str(headers, name)?.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(revision: &str, file: &str) -> HfFile { + HfFile { + repo: "owner/model".into(), + revision: revision.into(), + file: file.into(), + } + } + + #[test] + fn the_resolve_url_holds_each_part_as_a_segment() { + let url = resolve_url("https://huggingface.co", &file("main", "sub/m.gguf")).unwrap(); + assert_eq!( + url.as_str(), + "https://huggingface.co/owner/model/resolve/main/sub/m.gguf" + ); + // an endpoint with a path of its own, with or without a slash + for endpoint in ["http://mirror.test:8080/hf", "http://mirror.test:8080/hf/"] { + let url = resolve_url(endpoint, &file("main", "m.gguf")).unwrap(); + assert_eq!( + url.as_str(), + "http://mirror.test:8080/hf/owner/model/resolve/main/m.gguf" + ); + } + assert!(resolve_url("ftp://mirror.test", &file("main", "m.gguf")).is_err()); + assert!(resolve_url("not a url", &file("main", "m.gguf")).is_err()); + } + + #[test] + fn a_name_that_would_change_the_url_makes_none() { + for (revision, path) in [ + ("main", "../../other/model/resolve/main/m.gguf"), + ("main", "%2e%2e/m.gguf"), + ("main", "m.gguf?download=1"), + ("main", "m.gguf#x"), + ("main", "/m.gguf"), + ("main", "a\\m.gguf"), + ("..", "m.gguf"), + ("main?x", "m.gguf"), + ("main#x", "m.gguf"), + ("ma%69n", "m.gguf"), + ] { + let made = resolve_url("https://huggingface.co", &file(revision, path)); + assert!(made.is_err(), "{revision} {path}: {made:?}"); + } + let mut other_host = file("main", "m.gguf"); + other_host.repo = "owner@evil.test/model".into(); + assert!(resolve_url("https://huggingface.co", &other_host).is_err()); + } + + #[test] + fn a_pinned_copy_resolves_its_commit_and_not_the_branch_again() { + let endpoint = "https://huggingface.co"; + let branch = file("main", "m.gguf"); + let mut remote = HfRemote::new(&branch, endpoint, None).unwrap(); + let commit = "0123456789abcdef0123456789abcdef01234567"; + remote.pin(&branch.at(commit), endpoint).unwrap(); + // a retry after the signed URL expires asks for the copy's commit + assert_eq!( + remote.resolver.as_str(), + format!("{endpoint}/owner/model/resolve/{commit}/m.gguf") + ); + } + + #[test] + fn only_a_commit_id_is_taken_from_the_resolver() { + let with = |value: &str| { + let mut headers = HeaderMap::new(); + headers.insert("x-repo-commit", value.parse().unwrap()); + commit_header(&headers) + }; + let commit = "0123456789abcdef0123456789abcdef01234567"; + assert_eq!(with(commit).unwrap().as_deref(), Some(commit)); + for value in ["main", "../../../etc", "0123", "..", &commit.to_uppercase()] { + assert!(with(value).is_err(), "{value}"); + } + assert_eq!(commit_header(&HeaderMap::new()).unwrap(), None); + } +} diff --git a/crates/skippy-receipt-audit/src/claimed_file/tests.rs b/crates/skippy-receipt-audit/src/claimed_file/tests.rs new file mode 100644 index 00000000..7c801b16 --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_file/tests.rs @@ -0,0 +1,697 @@ +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::{Arc, Mutex}; + +use super::*; +use hf_file::is_commit; + +const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + +fn string(out: &mut Vec, s: &str) { + out.extend((s.len() as u64).to_le_bytes()); + out.extend(s.as_bytes()); +} + +/// A GGUF with one f32 matrix `w` of `rows` rows of four values, row `r` +/// holding `r` in every value. +fn gguf(rows: u64) -> Vec { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend(1u64.to_le_bytes()); + out.extend(1u64.to_le_bytes()); + string(&mut out, "general.architecture"); + out.extend(8u32.to_le_bytes()); + string(&mut out, "test"); + string(&mut out, "w"); + out.extend(2u32.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + out.extend(rows.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(0u64.to_le_bytes()); + out.resize(out.len().div_ceil(32) * 32, 0); + for r in 0..rows { + for _ in 0..4 { + out.extend((r as f32).to_le_bytes()); + } + } + out +} + +/// A GGUF whose header lists the tensor `w` twice, which the runtime's +/// loader refuses. +fn gguf_with_a_tensor_twice() -> Vec { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend(2u64.to_le_bytes()); + out.extend(0u64.to_le_bytes()); + for offset in [0u64, 32] { + string(&mut out, "w"); + out.extend(2u32.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + out.extend(2u64.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(offset.to_le_bytes()); + } + out.resize(out.len().div_ceil(32) * 32 + 64, 0); + out +} + +/// What the fixture server saw: per request, its method, path and whether +/// it carried the token. +type Seen = Arc>>; + +/// A resolver that redirects to a CDN path on the same server, which is +/// another origin because the redirect names 127.0.0.1 and the resolver +/// localhost. The repo in the path picks what the resolver says: +/// +/// - `owner/model`: the commit, the size and the redirect. +/// - `owner/nocommit`: no commit. +/// - `owner/badcommit`: a commit that is a path. +/// - `owner/direct`: the file itself, whose range requests it redirects. +fn serve(bytes: Vec) -> (String, Seen) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let seen: Seen = Arc::default(); + let log = seen.clone(); + let bytes = Arc::new(bytes); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let bytes = bytes.clone(); + let log = log.clone(); + std::thread::spawn(move || answer(stream, port, &bytes, &log)); + } + }); + (format!("http://localhost:{port}"), seen) +} + +fn answer(mut stream: TcpStream, port: u16, bytes: &[u8], seen: &Seen) { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let mut parts = line.split_whitespace(); + let (method, path) = ( + parts.next().unwrap().to_owned(), + parts.next().unwrap().to_owned(), + ); + let (mut range, mut token) = (None, false); + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + let header = header.trim_end(); + if header.is_empty() { + break; + } + let (name, value) = header.split_once(": ").unwrap(); + match name.to_ascii_lowercase().as_str() { + "range" => range = Some(value.trim_start_matches("bytes=").to_owned()), + "authorization" => token = value == "Bearer secret", + _ => {} + } + } + seen.lock() + .unwrap() + .push((method.clone(), path.clone(), token)); + if let Some(api) = path.strip_prefix("/api/models/owner/") { + let _ = stream.write_all(&commit_list(api)); + return; + } + if let Some(cdn) = path.strip_prefix("/cdn/") { + let repo = cdn.split('/').next().unwrap_or_default(); + let range = range.unwrap_or_default(); + if repo == "flood" { + flood(&mut stream, &range); + return; + } + let shifted = if repo == "shifted" { 16 } else { 0 }; + let _ = stream.write_all(&ranged(bytes, &range, shifted)); + return; + } + let size = format!("x-linked-size: {}\r\n", bytes.len()); + let commit = format!("x-repo-commit: {COMMIT}\r\n"); + let (repo, revision) = path + .strip_suffix("/sub/model.gguf") + .and_then(|p| p.split_once("/resolve/")) + .unwrap_or_default(); + let repo = repo.strip_prefix("/owner/").unwrap_or_default(); + let cdn = format!("Location: http://127.0.0.1:{port}/cdn/{repo}/model.gguf?sig=1\r\n"); + // like Hugging Face, which serves a file at any commit of the repo + let at = if is_commit(revision) { + revision + } else { + COMMIT + }; + let echoed = format!("x-repo-commit: {at}\r\n"); + let head = method == "HEAD"; + let response = match repo { + "model" if head => redirect(&[&cdn, &commit, &size]), + "echo" | "deep" | "shifted" | "flood" if head => redirect(&[&cdn, &echoed, &size]), + "nocommit" if head => redirect(&[&cdn, &size]), + "badcommit" if head => redirect(&[&cdn, "x-repo-commit: ../../../etc\r\n", &size]), + "direct" if head => format!( + "HTTP/1.1 200 OK\r\n{commit}{size}Content-Length: 0\r\nConnection: close\r\n\r\n" + ) + .into_bytes(), + "direct" if method == "GET" => redirect(&[&cdn]), + _ => not_found(), + }; + let _ = stream.write_all(&response); +} + +fn not_found() -> Vec { + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec() +} + +/// The newest commit of the branch `main` of `owner/echo`, then `COMMIT`, +/// then the oldest, which is on the second page. +const HEAD_COMMIT: &str = "1111111111111111111111111111111111111111"; +const OLD_COMMIT: &str = "2222222222222222222222222222222222222222"; +/// The commit of a pull request on `owner/echo`, on no branch. +const PR_COMMIT: &str = "3333333333333333333333333333333333333333"; + +/// The commit list of `api`, `{repo}/commits/{branch}?{query}`: for +/// `echo`, two pages; for `deep`, a page of other commits that always +/// links to one more. +fn commit_list(api: &str) -> Vec { + let (repo, rest) = api.split_once("/commits/").unwrap_or_default(); + let (branch, query) = rest.split_once('?').unwrap_or((rest, "")); + let second = query.split('&').any(|q| q == "p=1"); + let (ids, next): (Vec, Option<&str>) = match (repo, branch) { + ("echo", "main") if second => (vec![OLD_COMMIT.into()], None), + ("echo", "main") => ( + vec![HEAD_COMMIT.into(), COMMIT.into()], + Some("/api/models/owner/echo/commits/main?p=1&limit=1000"), + ), + ("deep", "main") => ( + vec!["4".repeat(40)], + Some("/api/models/owner/deep/commits/main?p=1&limit=1000"), + ), + _ => return not_found(), + }; + let body = serde_json::to_vec( + &ids.iter() + .map(|id| serde_json::json!({ "id": id, "title": "t" })) + .collect::>(), + ) + .unwrap(); + let link = next.map_or(String::new(), |next| { + format!("Link: <{next}>; rel=\"next\"\r\n") + }); + let mut out = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n{link}Content-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + out.extend(body); + out +} + +/// Bytes the flood answer sends, past any range a test asks for. +const FLOOD_BYTES: usize = 256 << 20; + +/// Answers a range request with the range it asked for, and then far more +/// body than that, with no length. +fn flood(stream: &mut TcpStream, range: &str) { + let head = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {range}/{}\r\nConnection: close\r\n\r\n", + FLOOD_BYTES + ); + if stream.write_all(head.as_bytes()).is_err() { + return; + } + let chunk = vec![0u8; 1 << 20]; + let mut sent = 0; + while sent < FLOOD_BYTES && stream.write_all(&chunk).is_ok() { + sent += chunk.len(); + } + FLOODED.fetch_add(sent, std::sync::atomic::Ordering::SeqCst); +} + +/// Bytes the flood answers got the client to take. +static FLOODED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn redirect(headers: &[&str]) -> Vec { + format!( + "HTTP/1.1 302 Found\r\n{}Content-Length: 0\r\nConnection: close\r\n\r\n", + headers.concat() + ) + .into_bytes() +} + +/// Answers `range` with its bytes; with a `shift`, a range past the +/// file's start with as many bytes from `shift` bytes on, and says so. +fn ranged(bytes: &[u8], range: &str, shift: usize) -> Vec { + let (start, end) = range + .split_once('-') + .map(|(s, e)| (s.parse::().unwrap(), e.parse::().unwrap())) + .unwrap(); + let shift = if start > 0 { shift } else { 0 }; + let (start, end) = (start + shift, end + shift); + let body = &bytes[start..=end]; + let mut out = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {start}-{end}/{}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len(), + body.len() + ) + .into_bytes(); + out.extend_from_slice(body); + out +} + +fn hf_file() -> HfFile { + HfFile::parse("owner/model@main/sub/model.gguf").unwrap() +} + +fn in_repo(repo: &str) -> HfFile { + HfFile::parse(&format!("owner/{repo}@main/sub/model.gguf")).unwrap() +} + +/// Every file under `dir`, to show an open that was refused wrote none. +fn files_under(dir: &Path) -> Vec { + let mut files = Vec::new(); + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + match entry.file_type() { + Ok(kind) if kind.is_dir() => files.extend(files_under(&path)), + _ => files.push(path), + } + } + files +} + +#[test] +fn a_hugging_face_file_is_read_by_range_into_a_pinned_copy() { + // past the megabytes the first read of the header takes + let bytes = gguf(1_000_000); + let (endpoint, seen) = serve(bytes.clone()); + let cache = tempfile::tempdir().unwrap(); + let claimed = open_hf(&hf_file(), &endpoint, Some("secret".into()), cache.path()).unwrap(); + assert_eq!( + claimed.path, + cache + .path() + .join("owner--model") + .join(COMMIT) + .join("sub/model.gguf") + ); + // the branch resolved to a commit, which the caller gets to keep + let pinned = format!("owner/model@{COMMIT}/sub/model.gguf"); + assert_eq!(claimed.identity, pinned); + let kept = claimed.pinned.clone().unwrap(); + assert!(kept.is_pinned()); + assert_eq!(kept.to_string(), pinned); + assert_eq!( + claimed.weights.row("w", 900_000).unwrap(), + vec![900_000.0; 4] + ); + let seen = seen.lock().unwrap().clone(); + // the token goes to the resolver, not to the CDN + assert!( + seen.iter() + .any(|(m, p, token)| m == "HEAD" && p.contains("/resolve/") && *token) + ); + assert!( + seen.iter() + .filter(|(_, p, _)| p.starts_with("/cdn/")) + .all(|(_, _, token)| !token) + ); + // the header took one request, the row one more + let fetches = seen.iter().filter(|(m, _, _)| m == "GET").count(); + assert_eq!(fetches, 2, "{seen:?}"); + // the copy holds what was read, not the file + let held = std::fs::read(&claimed.path).unwrap(); + assert_eq!(held.len(), bytes.len()); + let row = claimed.weights.row_range("w", 900_000).unwrap(); + let (start, end) = (row.0 as usize, (row.0 + row.1) as usize); + assert_eq!(held[start..end], bytes[start..end]); + assert!(held[start - 16..start].iter().all(|&b| b == 0)); +} + +#[test] +fn a_reopened_copy_reads_nothing_it_holds() { + let (endpoint, seen) = serve(gguf(1000)); + let cache = tempfile::tempdir().unwrap(); + open_hf(&hf_file(), &endpoint, None, cache.path()) + .unwrap() + .weights + .row("w", 3) + .unwrap(); + let before = seen.lock().unwrap().len(); + let claimed = open_hf(&hf_file(), &endpoint, None, cache.path()).unwrap(); + assert_eq!(claimed.weights.row("w", 3).unwrap(), vec![3.0; 4]); + let after: Vec<_> = seen.lock().unwrap()[before..].to_vec(); + // only the resolver again: the header and row were held + assert_eq!(after.len(), 1, "{after:?}"); + assert_eq!(after[0].0, "HEAD"); +} + +#[test] +fn a_moved_revision_is_refused_for_a_commit() { + let (endpoint, _) = serve(gguf(10)); + let cache = tempfile::tempdir().unwrap(); + // the fixture resolves every revision to its one commit + let moved = hf_file().at(&"f".repeat(40)); + assert!(open_hf(&moved, &endpoint, None, cache.path()).is_err()); + assert!(open_hf(&hf_file().at(COMMIT), &endpoint, None, cache.path()).is_ok()); +} + +#[test] +fn a_revision_the_resolver_does_not_pin_is_refused() { + let (endpoint, _) = serve(gguf(10)); + let cache = tempfile::tempdir().unwrap(); + // a branch, and no commit from the resolver: the copy would be of + // whatever the branch is at when a range is read + let refused = open_hf(&in_repo("nocommit"), &endpoint, None, cache.path()) + .err() + .unwrap() + .to_string(); + assert!(refused.contains("which commit"), "{refused}"); + // a commit names itself + let named = in_repo("nocommit").at(COMMIT); + let claimed = open_hf(&named, &endpoint, None, cache.path()).unwrap(); + assert_eq!(claimed.pinned, Some(named)); + // a commit that is a path names no directory of the cache + let refused = open_hf(&in_repo("badcommit"), &endpoint, None, cache.path()); + assert!(refused.is_err()); + assert_eq!(files_under(cache.path()).len(), 3, "the one good copy"); +} + +#[test] +fn a_receipt_must_name_a_commit() { + let cache = tempfile::tempdir().unwrap(); + // refused before any request: these reach no server + for name in [ + "owner/model@main/sub/model.gguf", + "owner/model@v1.0/sub/model.gguf", + "owner/model@0123456789abcdef/sub/model.gguf", + ] { + let error = open_named_by_receipt(name, cache.path()).err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(error.to_string().contains("not a commit"), "{error}"); + let file = HfFile::parse(name).unwrap(); + assert!(open_remote(&file, cache.path()).is_err()); + } + assert!(require_pinned(&hf_file().at(COMMIT)).is_ok()); + assert!(files_under(cache.path()).is_empty()); +} + +#[test] +fn a_name_out_of_a_receipt_never_opens_a_file_here() { + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("model.gguf"); + std::fs::write(&local, gguf(4)).unwrap(); + // the user may name the file + assert!(open(&local, dir.path()).is_ok()); + // a node may not: its name is a Hugging Face file or nothing + let cache = dir.path().join("cache"); + let named = local.to_str().unwrap(); + let refused = open_named_by_receipt(named, &cache).err().unwrap(); + assert!( + refused.to_string().contains("the receipt names"), + "{refused}" + ); + for name in ["model.gguf", "./model.gguf", "../model.gguf", ""] { + assert!(open_named_by_receipt(name, &cache).is_err(), "{name:?}"); + } + assert!(!cache.exists()); +} + +#[test] +fn a_name_that_is_a_path_writes_nothing_outside_the_cache() { + let (endpoint, seen) = serve(gguf(10)); + let dir = tempfile::tempdir().unwrap(); + let cache = dir.path().join("cache"); + let target = dir.path().join("authorized_keys"); + std::fs::write(&target, b"the user's keys").unwrap(); + let absolute = target.to_str().unwrap().to_owned(); + let names = [ + // the doubled slash makes the file an absolute path + format!("evil/m@main/{absolute}"), + format!("evil/m@{COMMIT}/{absolute}"), + format!("evil/m@main//{}", absolute.trim_start_matches('/')), + "evil/m@main/../../authorized_keys".to_owned(), + format!("evil/m@main/sub/../../../../{}", "authorized_keys"), + ]; + for name in &names { + assert_eq!(HfFile::parse(name), None, "{name}"); + assert!(open_named_by_receipt(name, &cache).is_err()); + assert!(open(Path::new(name), &cache).is_err()); + } + // a name built past the parser is checked again before it is a URL or + // a path + for file in [absolute.as_str(), "../../authorized_keys", "/x.gguf"] { + let built = hf_file().at(COMMIT).sibling(file); + assert!(open_hf(&built, &endpoint, None, &cache).is_err(), "{file}"); + } + assert_eq!(std::fs::read(&target).unwrap(), b"the user's keys"); + assert!(files_under(dir.path()).len() == 1, "only the user's file"); + assert!(seen.lock().unwrap().is_empty(), "no name reached a server"); +} + +#[cfg(unix)] +#[test] +fn a_symlinked_cache_directory_holds_no_copy() { + let (endpoint, _) = serve(gguf(10)); + let cache = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(elsewhere.path(), cache.path().join("owner--model")).unwrap(); + let refused = open_hf(&hf_file(), &endpoint, None, cache.path()) + .err() + .unwrap() + .to_string(); + assert!(refused.contains("symlink"), "{refused}"); + assert!(files_under(elsewhere.path()).is_empty()); +} + +#[test] +fn a_redirect_to_another_origin_carries_no_token() { + let bytes = gguf(1000); + let (endpoint, seen) = serve(bytes); + let cache = tempfile::tempdir().unwrap(); + // the resolver serves this file itself, then redirects its range + // requests to the CDN + let claimed = open_hf( + &in_repo("direct"), + &endpoint, + Some("secret".into()), + cache.path(), + ) + .unwrap(); + assert_eq!(claimed.weights.row("w", 7).unwrap(), vec![7.0; 4]); + let seen = seen.lock().unwrap().clone(); + let gets = |prefix: &str| -> Vec { + seen.iter() + .filter(|(method, path, _)| method == "GET" && path.starts_with(prefix)) + .map(|(_, _, token)| *token) + .collect() + }; + // the resolver's origin sees the token, the origin it redirects to not + assert!(!gets("/owner/direct/").is_empty()); + assert!(gets("/owner/direct/").iter().all(|token| *token)); + assert!(!gets("/cdn/").is_empty()); + assert!(gets("/cdn/").iter().all(|token| !token), "{seen:?}"); +} + +#[test] +fn a_header_the_loader_would_not_take_is_refused_at_open() { + let (endpoint, _) = serve(gguf_with_a_tensor_twice()); + let cache = tempfile::tempdir().unwrap(); + let error = open_hf(&hf_file(), &endpoint, None, cache.path()) + .err() + .unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + // and again from the copy, before a native load of it + let copy = cache + .path() + .join("owner--model") + .join(COMMIT) + .join("sub/model.gguf"); + let error = read_header(©).err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); +} + +#[test] +fn the_header_of_a_copy_checks_from_the_copy() { + let (endpoint, _) = serve(gguf(1000)); + let cache = tempfile::tempdir().unwrap(); + let claimed = open_hf(&hf_file(), &endpoint, None, cache.path()).unwrap(); + read_header(&claimed.path).unwrap(); + // a copy that lost its header is a hole, and no GGUF + let lost = cache.path().join("lost.gguf"); + std::fs::write(&lost, vec![0u8; 4096]).unwrap(); + let error = read_header(&lost).err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); +} + +/// Shard `no` (from 0) of `count`, holding an f32 matrix `name` of `rows` +/// rows of four values, row `r` holding `r`. +fn shard(no: u64, count: u64, name: &str, rows: u64) -> Vec { + let uint = |out: &mut Vec, key: &str, value: u64| { + string(out, key); + out.extend(10u32.to_le_bytes()); + out.extend(value.to_le_bytes()); + }; + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend(1u64.to_le_bytes()); + out.extend(2u64.to_le_bytes()); + uint(&mut out, "split.no", no); + uint(&mut out, "split.count", count); + string(&mut out, name); + out.extend(2u32.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + out.extend(rows.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(0u64.to_le_bytes()); + out.resize(out.len().div_ceil(32) * 32, 0); + for r in 0..rows { + for _ in 0..4 { + out.extend((r as f32).to_le_bytes()); + } + } + out +} + +#[test] +fn a_local_split_gguf_opens_every_shard() { + let dir = tempfile::tempdir().unwrap(); + for (no, name) in ["a", "b", "c"].iter().enumerate() { + let path = dir.path().join(format!("m-{:05}-of-00003.gguf", no + 1)); + std::fs::write(path, shard(no as u64, 3, name, 3 + no as u64)).unwrap(); + } + let first = dir.path().join("m-00001-of-00003.gguf"); + let claimed = open(&first, dir.path()).unwrap(); + assert_eq!(claimed.path, first); + assert_eq!(claimed.pinned, None); + assert_eq!(claimed.weights.row("a", 2).unwrap(), vec![2.0; 4]); + assert_eq!(claimed.weights.row("c", 4).unwrap(), vec![4.0; 4]); + read_header(&first).unwrap(); + + let second = dir.path().join("m-00002-of-00003.gguf"); + let refused = open(&second, dir.path()).err().unwrap().to_string(); + assert!(refused.contains("claim its first shard"), "{refused}"); +} + +#[test] +fn a_split_of_too_many_shards_opens_none() { + let (endpoint, seen) = serve(gguf(10)); + let cache = tempfile::tempdir().unwrap(); + let many = HfFile::parse("owner/model@main/sub/m-00001-of-99999.gguf").unwrap(); + let error = open_hf(&many, &endpoint, None, cache.path()).err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + // not even the first shard is asked for + assert!(seen.lock().unwrap().is_empty()); + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("m-00001-of-99999.gguf"); + std::fs::write(&first, shard(0, 99_999, "a", 3)).unwrap(); + let error = open(&first, dir.path()).err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); +} + +/// The requests the fixture saw whose path starts with `prefix`. +fn requests(seen: &Seen, prefix: &str) -> usize { + seen.lock() + .unwrap() + .iter() + .filter(|(_, path, _)| path.starts_with(prefix)) + .count() +} + +#[test] +fn a_commit_off_the_branch_is_refused_before_any_byte_of_it() { + let (endpoint, seen) = serve(gguf(10)); + // Hugging Face serves the file at a pull request's commit + let pr = in_repo("echo").at(PR_COMMIT); + let error = branch_history::check(&pr, "main", &endpoint, None) + .err() + .unwrap(); + assert!(NotOnBranch::caused(&error), "{error:#}"); + assert!(error.to_string().contains("pull request"), "{error}"); + // both pages of the branch's history were read, and nothing else + assert_eq!(requests(&seen, "/api/models/owner/echo/commits/main"), 2); + assert_eq!(seen.lock().unwrap().len(), 2, "{seen:?}"); +} + +#[test] +fn a_commit_on_the_branch_is_checked_once() { + let (endpoint, seen) = serve(gguf(10)); + for commit in [COMMIT, OLD_COMMIT] { + let file = in_repo("echo").at(commit); + branch_history::check(&file, "main", &endpoint, Some("secret")).unwrap(); + let cache = tempfile::tempdir().unwrap(); + assert!(open_hf(&file, &endpoint, None, cache.path()).is_ok()); + } + let asked = requests(&seen, "/api/"); + // the first page held the one commit, the second the other + assert_eq!(asked, 3); + // the token went with the list, which is at the resolver's origin + assert!( + seen.lock() + .unwrap() + .iter() + .all(|(_, p, token)| !p.starts_with("/api/") || *token) + ); + // the process keeps what it found + branch_history::check(&in_repo("echo").at(OLD_COMMIT), "main", &endpoint, None).unwrap(); + assert_eq!(requests(&seen, "/api/"), asked); +} + +#[test] +fn a_history_that_does_not_end_is_read_to_a_cap_and_is_no_audit() { + let (endpoint, seen) = serve(gguf(10)); + let file = in_repo("deep").at(PR_COMMIT); + let error = branch_history::check(&file, "main", &endpoint, None) + .err() + .unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(!NotOnBranch::caused(&error)); + assert_eq!(requests(&seen, "/api/"), branch_history::MAX_PAGES); + // a branch with no list is no audit either + let error = branch_history::check(&in_repo("echo").at(COMMIT), "dev", &endpoint, None) + .err() + .unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); +} + +#[test] +fn a_branch_is_no_commit_to_check() { + let cache = tempfile::tempdir().unwrap(); + let error = check_on_branch(&hf_file(), "main").err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(files_under(cache.path()).is_empty()); +} + +#[test] +fn a_range_answer_is_read_no_further_than_asked() { + let (endpoint, _) = serve(gguf(1_000_000)); + let cache = tempfile::tempdir().unwrap(); + // the header's first read is 8 MiB; the answer goes on to 256 MiB + let error = open_hf(&in_repo("flood"), &endpoint, None, cache.path()) + .err() + .unwrap(); + assert!(format!("{error:#}").contains("longer than"), "{error:#}"); + let taken = FLOODED.load(std::sync::atomic::Ordering::SeqCst); + assert!(taken < 64 << 20, "the client took {taken} bytes"); +} + +#[test] +fn a_range_answer_for_other_bytes_is_refused() { + let (endpoint, _) = serve(gguf(1_000_000)); + let cache = tempfile::tempdir().unwrap(); + let claimed = open_hf(&in_repo("shifted"), &endpoint, None, cache.path()).unwrap(); + let error = claimed.weights.row("w", 900_000).unwrap_err(); + assert!( + format!("{error:#}").contains("answered with the range"), + "{error:#}" + ); +} + +#[test] +fn copies_are_never_kept_under_the_shared_temporary_directory() { + let error = cache_root_in(None).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + let home = PathBuf::from("/home/u/.cache/skippy"); + assert_eq!( + cache_root_in(Some(home.clone())).unwrap(), + home.join("receipts").join("claimed") + ); +} diff --git a/crates/skippy-receipt-audit/src/claimed_model.rs b/crates/skippy-receipt-audit/src/claimed_model.rs new file mode 100644 index 00000000..bcbaef3e --- /dev/null +++ b/crates/skippy-receipt-audit/src/claimed_model.rs @@ -0,0 +1,46 @@ +//! The claimed GGUF as an audit needs it: one layer at a time for the glue +//! check, and the vocabulary for the token check. The native loader +//! ([`crate::native_model`]) is the one a client runs; tests give a toy. + +use std::path::PathBuf; + +use anyhow::Result; +use skippy_receipts::glue::GlueEvaluator; + +/// Loads the claimed model the native loader reads from a path: the GGUF, +/// or its sparse copy. +pub type LoadClaimedModel<'a> = &'a dyn Fn(PathBuf) -> Box; + +/// The ggml types of the KV cache a stage stored one layer's rows in, by +/// the layer's stored rows: K, then V. `None` keeps the default. The +/// auditor builds the layer with them. Only the types an audit covers +/// reach it, f16 and f32 ([`skippy_receipts::cache_types::audited`]): a +/// receipt from a quantized cache is not audited. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CacheTypes { + pub k: Option, + pub v: Option, +} + +/// The claimed GGUF on this machine, as the audit needs it. +pub trait ClaimedModel { + /// Runs `check` with one layer of the model loaded alone, with a KV + /// cache of `cache` types. + fn with_layer( + &self, + layer: u32, + cache: CacheTypes, + check: &mut dyn FnMut(&dyn GlueEvaluator) -> Result<()>, + ) -> Result<()>; + /// The text of `tokens`. + fn detokenize(&self, tokens: &[i32]) -> Result; + /// The tokens of `text`, with special tokens parsed and none added, as + /// the runtime reads a tag of its reasoning-budget sampler. + fn tokenize(&self, text: &str) -> Result>; + /// The bytes of the text of one token. A control token gives its name. + fn token_piece(&self, token: i32) -> Result>; + /// Whether `token` ends generation, so it adds no text to a response. + fn is_end_of_generation(&self, token: i32) -> Result; + /// The runtime the glue evaluation runs, as a receipt names it. + fn runtime(&self) -> String; +} diff --git a/crates/skippy-receipt-audit/src/head_key_file.rs b/crates/skippy-receipt-audit/src/head_key_file.rs new file mode 100644 index 00000000..3224dd65 --- /dev/null +++ b/crates/skippy-receipt-audit/src/head_key_file.rs @@ -0,0 +1,128 @@ +//! Where the client keeps its secret head key for a claimed model, and its +//! first build. The key lives only on this machine, readable by its owner +//! alone: a node that learned it could change logits the check would miss. +//! +//! One key checks every node that serves the model, and whether a check +//! with it passes is a bit a node learns about it. So a key that refused a +//! node's logits is dropped, and the next audit builds a fresh one. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{Context, Result}; +use sha2::{Digest, Sha256}; +use skippy_receipts::head::key::HeadKey; +use skippy_receipts::weights::WeightFile; + +/// The key file for the claimed model `identity` names. +pub fn path_for(identity: &str) -> PathBuf { + let name = hex::encode(&Sha256::digest(identity.as_bytes())[..16]); + skippy_model_hf::application_cache_dir() + .join("receipts") + .join("head-keys") + .join(format!("{name}.json")) +} + +/// The key at `path`, or a fresh one built from `weights` and kept there, +/// with the seconds the build took. A file that is no key, or a key that +/// does not fit the model's output matrix or cannot check with it, is +/// built again: kept, it would leave the head unchecked for good. +pub fn load_or_build(path: &Path, weights: &WeightFile) -> Result<(HeadKey, Option)> { + if let Some(key) = std::fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|key| key.fits(weights)) + { + return Ok((key, None)); + } + let started = Instant::now(); + let key = HeadKey::build(weights, rand::random())?; + let seconds = started.elapsed().as_secs_f64(); + save(path, &key)?; + Ok((key, Some(seconds))) +} + +/// Drops the key at `path`, after a check with it refused a node's logits. +/// A file that is already gone is fine. +pub fn discard(path: &Path) -> Result<()> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error).with_context(|| format!("remove {}", path.display())), + } +} + +fn save(path: &Path, key: &HeadKey) -> Result<()> { + let parent = path.parent().context("a key path has a directory")?; + std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; + let temp = path.with_extension(format!("json.{}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options + .open(&temp) + .with_context(|| format!("write {}", temp.display()))?; + file.write_all(&serde_json::to_vec(key)?)?; + file.sync_all()?; + std::fs::rename(&temp, path).with_context(|| format!("write {}", path.display())) +} + +#[cfg(test)] +mod tests { + use skippy_receipts::toy_turn::weights; + + use super::*; + + #[test] + fn a_key_is_built_once_and_read_back() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("keys").join("toy.json"); + let weights = weights(); + let (built, seconds) = load_or_build(&path, &weights).unwrap(); + assert!(seconds.is_some()); + let (read, seconds) = load_or_build(&path, &weights).unwrap(); + assert!(seconds.is_none()); + assert_eq!(read, built); + } + + #[test] + fn a_file_that_cannot_check_is_built_again() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("toy.json"); + let weights = weights(); + let (key, _) = load_or_build(&path, &weights).unwrap(); + let mut json = serde_json::to_value(&key).unwrap(); + // a key that still parses and names the right matrix, with a + // vector missing: every check with it would stop with an error + json["vectors"].as_array_mut().unwrap().pop(); + for broken in [json.to_string(), "not a key".to_owned(), String::new()] { + std::fs::write(&path, broken).unwrap(); + let (rebuilt, seconds) = load_or_build(&path, &weights).unwrap(); + assert!(seconds.is_some(), "the broken key was kept"); + assert!(rebuilt.fits(&weights)); + assert_ne!(rebuilt, key); + // and the file now holds the key that was built + assert_eq!(load_or_build(&path, &weights).unwrap().0, rebuilt); + } + } + + #[test] + fn a_discarded_key_is_replaced_by_a_fresh_one() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("toy.json"); + let weights = weights(); + let (first, _) = load_or_build(&path, &weights).unwrap(); + discard(&path).unwrap(); + assert!(!path.exists()); + // dropping it twice is fine + discard(&path).unwrap(); + let (second, seconds) = load_or_build(&path, &weights).unwrap(); + assert!(seconds.is_some()); + assert_ne!(second, first); + } +} diff --git a/crates/skippy-receipt-audit/src/lib.rs b/crates/skippy-receipt-audit/src/lib.rs new file mode 100644 index 00000000..a18a02f6 --- /dev/null +++ b/crates/skippy-receipt-audit/src/lib.rs @@ -0,0 +1,31 @@ +//! The audit of an inference receipt against a claimed GGUF, on the +//! client's own machine. +//! +//! A client that received a turn and its receipt gives both to +//! [`turn_audit::audit_turn`], with the claimed model +//! ([`turn_audit::ClaimedSetup`]) and a way to send the challenge to the +//! node ([`turn_audit::OpenChallenge`]). The audit draws the challenge from +//! the VRF of the turn root, checks the node's opening against the claimed +//! GGUF, and ends one of four ways ([`outcome::Outcome`]). +//! [`recheck::recheck_evidence`] runs the same checks again on the +//! evidence an audit kept. +//! +//! The crate sends no chat request and prints nothing. `skippy-commands` +//! does both for `skippy audit-receipt` and `skippy recheck-receipt`, and +//! a Mesh node audits the turns its peers served. + +pub mod attention_audit; +pub mod chat_reply; +pub mod claimed_file; +pub mod claimed_model; +mod head_key_file; +pub mod native_model; +mod node_text; +mod opening_checks; +pub mod outcome; +pub mod output; +pub mod recheck; +pub mod recurrent_audit; +pub mod report_text; +mod token_check; +pub mod turn_audit; diff --git a/crates/skippy-receipt-audit/src/native_model.rs b/crates/skippy-receipt-audit/src/native_model.rs new file mode 100644 index 00000000..f309b042 --- /dev/null +++ b/crates/skippy-receipt-audit/src/native_model.rs @@ -0,0 +1,527 @@ +//! The receipt auditor's view of the claimed GGUF: one layer at a time, +//! loaded alone on the CPU, and the vocabulary of its first layer. +//! +//! A node names the claimed GGUF, so its bytes are whatever that node +//! published. The native loader reads the file only after the header +//! passed the strict Rust reading an audit opens it with +//! ([`claimed_file::read_header`]): the runtime's loader then sees only +//! headers with each name once, in UTF-8, and tensors of known types laid +//! inside the file. The metadata values the native code asserts on, which +//! would end the process, are checked first too (`loader_asserts`), and so +//! are the token ids a receipt hands the tokenizer. + +use std::cell::{OnceCell, RefCell}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use crate::claimed_file; +use crate::claimed_model::{CacheTypes, ClaimedModel}; +use anyhow::{Context, Result, bail}; +use skippy_receipts::attention::{ + AttentionDescriptor, AttentionLayout, AttentionOp, OutputRotation, Window, q_rounding, +}; +use skippy_receipts::glue::{ + GlueEvaluator, GlueInput, GlueOutput, GlueRequest, GlueTensor, GlueValues, StoredRowError, +}; +use skippy_receipts::layer_tensors::{GGML_F32, GGML_I32, TensorKind, decode_f32_bytes}; +use skippy_runtime::{ + GgufStageRuntimePlan, ReceiptAttentionOp, ReceiptAttentionWindow, ReceiptGlueInput, + ReceiptGlueRequestRef, ReceiptGlueTensor, ReceiptGlueValues, RuntimeConfig, StageModel, + plan_gguf_stage_runtime_plan_for_range, receipt_stored_row_error, +}; + +mod loader_asserts; + +/// Context of the stage the planner sizes; the glue context sets its own. +const PLAN_CTX: u32 = 256; + +pub struct NativeGlueEvaluator { + model: StageModel, +} + +/// The layer after `layer`, where its stage ends. +fn layer_end(layer: u32) -> Result { + layer + .checked_add(1) + .with_context(|| format!("layer {layer} is the last a stage can name")) +} + +/// The stage plan of `layer` alone. The native planner reads the header of +/// the GGUF and no tensor, so the plan of a layer is the same for as long +/// as the header is. +fn plan_layer(path: &Path, layer: u32) -> Result { + plan_gguf_stage_runtime_plan_for_range(path, (layer, layer_end(layer)?), PLAN_CTX, 1) + .with_context(|| format!("plan layer {layer} of {}", path.display())) +} + +impl NativeGlueEvaluator { + /// Loads `layer` of the GGUF at `path` as a single-layer CPU stage, by + /// its `plan`, with a KV cache of `cache` types. Only + /// [`NativeClaimedModel`] loads, after the header passed the strict + /// check. + fn load( + path: &Path, + layer: u32, + cache: CacheTypes, + plan: GgufStageRuntimePlan, + ) -> Result { + let mut config = RuntimeConfig { + layer_start: layer, + layer_end: layer_end(layer)?, + ctx_size: PLAN_CTX, + // the CPU only: an auditor needs no GPU + n_gpu_layers: 0, + op_offload: Some(false), + kv_offload: Some(false), + ..RuntimeConfig::default() + }; + plan.apply_to(&mut config); + if let Some(k) = cache.k { + config.cache_type_k = k; + } + if let Some(v) = cache.v { + config.cache_type_v = v; + } + let model = StageModel::open(path, &config) + .with_context(|| format!("load layer {layer} of {}", path.display()))?; + Ok(Self { model }) + } +} + +fn input_ref(input: &GlueInput) -> ReceiptGlueInput<'_> { + ReceiptGlueInput { + kind: input.kind.code(), + index: input.index, + len: input.len, + values: match &input.values { + GlueValues::F32(v) => ReceiptGlueValues::F32(v), + GlueValues::I32(v) => ReceiptGlueValues::I32(v), + }, + } +} + +/// Keeps the first `n_cols` columns: the native evaluation pads to at least two. +fn glue_tensor(t: ReceiptGlueTensor, n_cols: usize) -> Result> { + let Some(kind) = TensorKind::from_code(t.kind) else { + return Ok(None); + }; + if t.n_cols < n_cols { + bail!( + "the evaluation reported {} columns of {}, not {n_cols}", + t.n_cols, + t.name + ); + } + let bytes = &t.values[..t.len * n_cols * 4]; + let values = match t.ggml_type { + GGML_F32 => GlueValues::F32(decode_f32_bytes(bytes)), + GGML_I32 => GlueValues::I32( + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| i32::from_le_bytes(*c)) + .collect(), + ), + other => bail!("the evaluation reported {} as ggml type {other}", t.name), + }; + Ok(Some(GlueTensor { + layer: t.layer, + kind, + index: t.index, + flags: t.flags, + name: t.name, + len: t.len, + values, + })) +} + +/// The claimed GGUF. Layer 0 stays loaded for the vocabulary; every check +/// loads its layer for that check and frees it. A sparse copy holds more +/// bytes after each audit's fetches, and the loader copies a tensor when it +/// loads it, so a layer kept from an earlier check would miss rows fetched +/// since (the anchors' token embeddings, for one). +/// +/// What does not change between loads is kept: that the header passed the +/// strict check, and each layer's stage plan, which the planner derives +/// from the header alone. The load itself reads the file again every time. +/// A header that passed every check before the native code. +struct CheckedHeader { + weights: skippy_receipts::weights::WeightFile, + checked: loader_asserts::Checked, +} + +pub struct NativeClaimedModel { + path: PathBuf, + first: OnceCell, + /// The header, once it passed the strict check and the checks of what + /// the native code asserts on. + header: OnceCell, + /// The stage plan of each layer loaded so far. + plans: RefCell>, +} + +impl NativeClaimedModel { + pub fn new(path: PathBuf) -> Self { + Self { + path, + first: OnceCell::new(), + header: OnceCell::new(), + plans: RefCell::new(BTreeMap::new()), + } + } + + fn first(&self) -> Result<&NativeGlueEvaluator> { + if let Some(first) = self.first.get() { + return Ok(first); + } + let first = self.open_layer(0, CacheTypes::default())?; + Ok(self.first.get_or_init(|| first)) + } + + /// Checks the header strictly, once: the native planner and loader run + /// only on a file that passed. + fn checked_header(&self) -> Result<&CheckedHeader> { + if let Some(header) = self.header.get() { + return Ok(header); + } + let weights = claimed_file::read_header(&self.path) + .with_context(|| format!("check the GGUF header of {}", self.path.display()))?; + let checked = loader_asserts::check(&weights) + .with_context(|| format!("check the GGUF metadata of {}", self.path.display()))?; + Ok(self + .header + .get_or_init(|| CheckedHeader { weights, checked })) + } + + /// Refuses a token id the vocabulary does not hold: the native + /// tokenizer throws on it where nothing catches the exception, which + /// ends the process. A receipt names the ids. + fn check_tokens(&self, tokens: &[i32]) -> Result<()> { + let vocabulary = self.checked_header()?.checked.vocabulary; + if let Some(token) = tokens + .iter() + .find(|&&token| !u64::try_from(token).is_ok_and(|id| id < vocabulary)) + { + bail!("the token {token} is not in the claimed model's vocabulary of {vocabulary}"); + } + Ok(()) + } + + /// Loads `layer` alone from the file as it is now, by a plan made once. + fn open_layer(&self, layer: u32, cache: CacheTypes) -> Result { + let header = self.checked_header()?; + loader_asserts::check_layer(&header.weights, layer)?; + let known = self.plans.borrow().get(&layer).cloned(); + let plan = match known { + Some(plan) => plan, + None => { + let plan = plan_layer(&self.path, layer)?; + self.plans.borrow_mut().insert(layer, plan.clone()); + plan + } + }; + NativeGlueEvaluator::load(&self.path, layer, cache, plan) + } +} + +impl ClaimedModel for NativeClaimedModel { + fn with_layer( + &self, + layer: u32, + cache: CacheTypes, + check: &mut dyn FnMut(&dyn GlueEvaluator) -> Result<()>, + ) -> Result<()> { + check(&self.open_layer(layer, cache)?) + } + + fn detokenize(&self, tokens: &[i32]) -> Result { + self.check_tokens(tokens)?; + self.first()?.model.detokenize(tokens) + } + + fn tokenize(&self, text: &str) -> Result> { + self.first()?.model.tokenize(text, false) + } + + fn token_piece(&self, token: i32) -> Result> { + self.check_tokens(&[token])?; + self.first()?.model.detokenize_bytes(&[token]) + } + + fn is_end_of_generation(&self, token: i32) -> Result { + self.check_tokens(&[token])?; + self.first()?.model.token_is_eog(token) + } + + fn runtime(&self) -> String { + skippy_receipts::turn::runtime_identity( + skippy_runtime::ABI_VERSION_MAJOR, + skippy_runtime::ABI_VERSION_MINOR, + skippy_runtime::ABI_VERSION_PATCH, + &skippy_runtime::receipt_runtime_source(), + ) + } +} + +impl GlueEvaluator for NativeGlueEvaluator { + fn evaluate(&self, request: &GlueRequest) -> Result { + let inputs: Vec> = request.inputs.iter().map(input_ref).collect(); + let result = self.model.eval_receipt_glue(&ReceiptGlueRequestRef { + layer: request.layer, + positions: &request.positions, + residual: &request.residual, + inputs: &inputs, + })?; + let n_cols = request.positions.len(); + let tensors = result + .tensors + .into_iter() + .map(|t| glue_tensor(t, n_cols)) + .filter_map(Result::transpose) + .collect::>()?; + Ok(GlueOutput { + tensors, + unchecked_weights: result.unchecked_weights, + attention: result.attention.iter().map(attention_descriptor).collect(), + }) + } + + fn evaluate_region(&self, request: &GlueRequest) -> Result { + let inputs: Vec> = request.inputs.iter().map(input_ref).collect(); + let result = self.model.eval_receipt_region(&ReceiptGlueRequestRef { + layer: request.layer, + positions: &request.positions, + residual: &request.residual, + inputs: &inputs, + })?; + let n_cols = request.positions.len(); + let tensors = result + .tensors + .into_iter() + .map(|t| { + // a state has a column per sequence, and the region is the first + let state = TensorKind::from_code(t.kind) == Some(TensorKind::MixingStateOut); + glue_tensor(t, if state { 1 } else { n_cols }) + }) + .filter_map(Result::transpose) + .collect::>()?; + Ok(GlueOutput { + tensors, + unchecked_weights: result.unchecked_weights, + attention: Vec::new(), + }) + } + + fn entry(&self, tokens: &[i32], positions: &[i32]) -> Result> { + let result = self.model.eval_receipt_entry(tokens, positions)?; + let residual = result + .tensors + .into_iter() + .find(|t| t.layer == 0 && TensorKind::from_code(t.kind) == Some(TensorKind::Residual)) + .context("the evaluation reported no input of layer 0")?; + match glue_tensor(residual, tokens.len())? { + Some(GlueTensor { + values: GlueValues::F32(values), + .. + }) => Ok(values), + _ => bail!("the input of layer 0 is not f32"), + } + } + + fn stored_row_error( + &self, + ggml_type: i32, + stored: &[u8], + computed: &[f32], + ) -> Result { + let error = receipt_stored_row_error(ggml_type, stored, computed)?; + Ok(StoredRowError { + stored: error.stored, + rounding: error.rounding, + norm: error.norm, + }) + } +} + +/// The claimed model the audit loads layers of from `path`. +pub fn load_claimed_model(path: PathBuf) -> Box { + Box::new(NativeClaimedModel::new(path)) +} + +/// An attention op of the auditor's graph, as the receipt check describes it. +fn attention_descriptor(op: &ReceiptAttentionOp) -> AttentionDescriptor { + let a = op.op.as_ref().map_err(Clone::clone)?; + Ok(AttentionLayout { + layer: op.layer, + op: AttentionOp { + n_head: a.n_head, + n_head_kv: a.n_head_kv, + head_dim_k: a.head_dim_k, + head_dim_v: a.head_dim_v, + scale: f64::from(a.scale), + softcap: f64::from(a.softcap), + sinks: a.sinks.clone(), + output_rotation: a + .output_rotation + .clone() + .map(|(n, matrix)| OutputRotation { n, matrix }), + q_rounding: a + .q_rounding + .map(q_rounding) + .transpose() + .map_err(|e| e.to_string())?, + window: match a.window { + ReceiptAttentionWindow::Causal => Window::Causal, + ReceiptAttentionWindow::Sliding(n) => Window::Sliding(n), + ReceiptAttentionWindow::Chunked(n) => Window::Chunked(n), + }, + }, + q_input: a.q_input, + k_store: a.k_store, + v_store: a.v_store, + output: a.output, + output_gate: a.output_gate, + }) +} + +#[cfg(test)] +mod tests { + use skippy_receipts::weights::limits::CannotAudit; + + use super::*; + + fn string(out: &mut Vec, s: &str) { + out.extend((s.len() as u64).to_le_bytes()); + out.extend(s.as_bytes()); + } + + /// A GGUF with a header only: `tensors`, by name and offset, each two + /// rows of four f32, and 64 bytes of data. + fn gguf(tensors: &[(&[u8], u64)]) -> Vec { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend((tensors.len() as u64).to_le_bytes()); + out.extend(1u64.to_le_bytes()); + string(&mut out, "general.architecture"); + out.extend(8u32.to_le_bytes()); + string(&mut out, "llama"); + for (name, offset) in tensors { + out.extend((name.len() as u64).to_le_bytes()); + out.extend(*name); + out.extend(2u32.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + out.extend(2u64.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(offset.to_le_bytes()); + } + out.resize(out.len().div_ceil(32) * 32 + 64, 0); + out + } + + /// The native planner and loader would abort the test on these files, + /// or read past them: the strict check answers first, with an error. + #[test] + fn a_header_that_fails_the_strict_check_is_never_loaded() { + let dir = tempfile::tempdir().unwrap(); + let cases: [(&str, Vec); 5] = [ + ("a tensor twice", gguf(&[(b"blk.0.w", 0), (b"blk.0.w", 32)])), + ( + "tensors that overlap", + gguf(&[(b"blk.0.a", 0), (b"blk.0.b", 0)]), + ), + ("a tensor off the alignment", gguf(&[(b"blk.0.a", 16)])), + ( + "a tensor past the file", + gguf(&[(b"blk.0.a", 0), (b"blk.0.b", 32), (b"blk.0.c", 64)]), + ), + ("a name that is not UTF-8", gguf(&[(b"blk.0.\xff", 0)])), + ]; + for (what, bytes) in cases { + let path = dir.path().join("claimed.gguf"); + std::fs::write(&path, bytes).unwrap(); + let model = load_claimed_model(path.clone()); + let loaded = model.with_layer(0, CacheTypes::default(), &mut |_| Ok(())); + let error = loaded.err().unwrap_or_else(|| panic!("{what} loaded")); + assert!(CannotAudit::caused(&error), "{what}: {error:#}"); + let error = model.detokenize(&[1]).err().unwrap(); + assert!(CannotAudit::caused(&error), "{what}: {error:#}"); + } + } + + /// A GGUF the strict header check passes whose `block_count` is 0. + fn no_layers() -> Vec { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend(1u64.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + string(&mut out, "general.architecture"); + out.extend(8u32.to_le_bytes()); + string(&mut out, "llama"); + for (key, value) in [ + ("llama.context_length", 4096u32), + ("llama.embedding_length", 4), + ("llama.block_count", 0), + ] { + string(&mut out, key); + out.extend(4u32.to_le_bytes()); + out.extend(value.to_le_bytes()); + } + string(&mut out, "token_embd.weight"); + out.extend(2u32.to_le_bytes()); + out.extend(4u64.to_le_bytes()); + out.extend(2u64.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(0u64.to_le_bytes()); + out.resize(out.len().div_ceil(32) * 32 + 32, 0); + out + } + + /// The file the child of the test below opens. + const HOSTILE_GGUF: &str = "SKIPPY_RECEIPT_AUDIT_TEST_HOSTILE_GGUF"; + + /// In the child process only: opens a layer of the file, which the + /// checks must refuse before the native planner aborts on it. + #[test] + fn hostile_metadata_child() { + let Some(path) = std::env::var_os(HOSTILE_GGUF) else { + return; + }; + let model = load_claimed_model(PathBuf::from(path)); + let error = model + .with_layer(0, CacheTypes::default(), &mut |_| Ok(())) + .unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(format!("{error:#}").contains("block_count"), "{error:#}"); + let error = model.detokenize(&[0]).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + } + + /// A file the strict header check passes, with a `block_count` of 0, + /// on which the native planner asserts and the process ends. Run in a + /// child process, so an abort fails this test and no other. + #[test] + fn hostile_metadata_never_reaches_the_native_code() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("claimed.gguf"); + std::fs::write(&path, no_layers()).unwrap(); + claimed_file::read_header(&path).unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "native_model::tests::hostile_metadata_child", + "--test-threads=1", + ]) + .env(HOSTILE_GGUF, &path) + .stdout(std::process::Stdio::null()) + .status() + .unwrap(); + assert!(status.success(), "the child ended with {status:?}"); + } + + #[test] + fn the_last_layer_number_has_no_stage() { + assert_eq!(layer_end(7).unwrap(), 8); + assert!(layer_end(u32::MAX).is_err()); + } +} diff --git a/crates/skippy-receipt-audit/src/native_model/loader_asserts.rs b/crates/skippy-receipt-audit/src/native_model/loader_asserts.rs new file mode 100644 index 00000000..d64962d1 --- /dev/null +++ b/crates/skippy-receipt-audit/src/native_model/loader_asserts.rs @@ -0,0 +1,391 @@ +//! The metadata values on which the native loader, planner and graph +//! builders assert, checked in Rust before any of them sees the claimed +//! GGUF. +//! +//! A `GGML_ASSERT` or `GGML_ABORT` ends the process, and in Mesh the +//! process is the node. A node names the claimed GGUF, so each value below +//! is refused here, as no audit, instead of reaching an assert. The sites +//! are of the pinned llama.cpp. The list covers the code every model +//! reaches and the common rules of the graph builders; it does not cover +//! every builder of every architecture (see `docs/design/RECEIPTS.md`, +//! open limitations). + +use anyhow::Result; +use skippy_receipts::weights::limits::refuse; +use skippy_receipts::weights::{MetaArray, MetaValue, TokenList, WeightFile}; + +/// `LLAMA_MAX_LAYERS`. +const MAX_LAYERS: u64 = 512; +/// `LLAMA_MAX_EXPERTS`. +const MAX_EXPERTS: u64 = 1024; +/// The longest training context accepted. The receipts glue sizes a region +/// from it; real models train on at most about a million positions. +const MAX_CONTEXT_LENGTH: u64 = 1 << 22; +/// The tokenizers whose load and tokenization paths were checked: a +/// SentencePiece vocabulary, a byte-level BPE one, and Gemma 4's. +const TOKENIZERS: [&str; 3] = ["llama", "gpt2", "gemma4"]; +/// `LLAMA_ROPE_SCALING_TYPES`. +const ROPE_SCALING_TYPES: [&str; 4] = ["none", "linear", "yarn", "longrope"]; +/// `LLM_CLS_ACT_TYPES_FROM_STRING`. +const CLASSIFIER_ACTIVATIONS: [&str; 3] = ["gelu", "silu", "tanh"]; +/// The architectures whose graph divides by the head count of layer 0. +const DIVIDES_BY_HEAD_COUNT: [&str; 3] = ["gemma2", "gemma3", "deepseek2"]; +/// Gemma 3n reads the KV cache of layer 19 from layer 20 on. +const GEMMA3N_SHARED_KV_FROM: u32 = 20; + +/// What the native code may be given after the checks pass. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Checked { + /// Tokens of the vocabulary: a token id at or past it makes the + /// tokenizer throw where nothing catches it. + pub(super) vocabulary: u64, +} + +/// Checks the metadata of the claimed GGUF the native loader asserts on. +pub(super) fn check(weights: &WeightFile) -> Result { + let meta = Meta { weights }; + let arch = meta.string("general.architecture")?; + let layers = check_layers(&meta, &arch)?; + check_experts(&meta, &arch)?; + check_heads(&meta, &arch, layers)?; + check_rope(&meta, &arch)?; + check_options(&meta, &arch)?; + let vocabulary = check_vocabulary(&meta)?; + Ok(Checked { vocabulary }) +} + +/// Checks that a stage of `layer` alone loads: a layer that reads the KV +/// cache of another layer makes the cache assert when that layer is +/// outside the stage. +pub(super) fn check_layer(weights: &WeightFile, layer: u32) -> Result<()> { + let meta = Meta { weights }; + let arch = meta.string("general.architecture")?; + let shared_from = match arch.as_str() { + "gemma3n" => Some(u64::from(GEMMA3N_SHARED_KV_FROM)), + "gemma4" => { + let layers = meta.int(&format!("{arch}.block_count"))?.unwrap_or(0); + let shared = meta + .int(&format!("{arch}.attention.shared_kv_layers"))? + .unwrap_or(0); + Some(layers.saturating_sub(shared)) + } + _ => None, + }; + match shared_from { + Some(from) if u64::from(layer) >= from => refuse(format!( + "layer {layer} of this {arch} model reads the KV cache of an earlier layer, which a one-layer stage does not hold" + )), + _ => Ok(()), + } +} + +/// The metadata of the file, read for the checks. +struct Meta<'a> { + weights: &'a WeightFile, +} + +impl Meta<'_> { + fn value(&self, key: &str) -> Option<&MetaValue> { + self.weights.metadata.get(key) + } + + fn string(&self, key: &str) -> Result { + match self.value(key) { + Some(MetaValue::Str(text)) => Ok(text.clone()), + _ => refuse(format!("its metadata has no string {key}")), + } + } + + fn optional_string(&self, key: &str) -> Result> { + match self.value(key) { + None => Ok(None), + Some(MetaValue::Str(text)) => Ok(Some(text.clone())), + Some(_) => refuse(format!("its metadata {key} is not a string")), + } + } + + fn int(&self, key: &str) -> Result> { + match self.value(key) { + None => Ok(None), + Some(MetaValue::Int(value)) => Ok(Some(*value)), + Some(_) => refuse(format!("its metadata {key} is not an integer")), + } + } + + /// A value that is one integer, or one per layer: the values, or none. + fn per_layer(&self, key: &str) -> Result>> { + if let Some(value) = self.int(key)? { + return Ok(Some(vec![i64::try_from(value).unwrap_or(i64::MAX)])); + } + match self.weights.arrays.get(key) { + Some(MetaArray::Ints(values)) => Ok(Some(values.clone())), + Some(MetaArray::Tokens(_)) => refuse(format!("its metadata {key} is not integers")), + // an array of no integers, which the loader refuses with an error + None => Ok(None), + } + } + + fn tokens(&self) -> Result<&TokenList> { + match self.weights.arrays.get("tokenizer.ggml.tokens") { + Some(MetaArray::Tokens(tokens)) => Ok(tokens), + _ => refuse("its metadata has no list of tokens"), + } + } +} + +/// `block_count` in 1 to 512 (`llama-model.cpp`, `load_hparams`), and +/// fewer `nextn_predict_layers`, each with its tensors. +fn check_layers(meta: &Meta<'_>, arch: &str) -> Result { + let layers = meta.int(&format!("{arch}.block_count"))?.unwrap_or(0); + if layers == 0 || layers > MAX_LAYERS { + return refuse(format!( + "its block_count is {layers}, not 1 to {MAX_LAYERS}" + )); + } + let nextn = meta + .int(&format!("{arch}.nextn_predict_layers"))? + .unwrap_or(0); + if nextn >= layers { + return refuse(format!( + "its nextn_predict_layers is {nextn}, not fewer than its {layers} layers" + )); + } + // without these the multi-token head's tensors become optional, and a + // graph reads them anyway + for layer in layers - nextn..layers { + let name = format!("blk.{layer}.nextn.eh_proj.weight"); + if !meta.weights.tensors.contains_key(&name) { + return refuse(format!( + "it names {nextn} next-token layers and has no {name}" + )); + } + } + if arch == "gemma4" { + let shared = meta + .int(&format!("{arch}.attention.shared_kv_layers"))? + .unwrap_or(0); + if shared.saturating_add(2) > layers { + return refuse(format!( + "its {shared} layers that share a KV cache leave fewer than 2 of its {layers}" + )); + } + } + if arch == "mistral-large4" { + return refuse( + "a layer of mistral-large4 may read the KV cache of another, which this client cannot tell from the header", + ); + } + Ok(layers) +} + +/// The expert counts `load_hparams` asserts on. +fn check_experts(meta: &Meta<'_>, arch: &str) -> Result<()> { + let experts = meta.int(&format!("{arch}.expert_count"))?.unwrap_or(0); + let used = meta + .per_layer(&format!("{arch}.expert_used_count"))? + .unwrap_or_default(); + let groups = meta + .int(&format!("{arch}.expert_group_count"))? + .unwrap_or(0); + let groups_used = meta + .int(&format!("{arch}.expert_group_used_count"))? + .unwrap_or(0); + if experts > MAX_EXPERTS { + return refuse(format!( + "its expert_count is {experts}, more than {MAX_EXPERTS}" + )); + } + if used.iter().any(|&n| n < 0 || n > i64::from(u32::MAX)) { + return refuse(format!("its expert_used_count {used:?} is out of range")); + } + let most_used = used.iter().copied().max().unwrap_or(0) as u64; + let fits = if experts > 0 { + most_used > 0 + && most_used <= experts + && groups < experts + && (groups <= 1 + || (experts.is_multiple_of(groups) && groups_used > 0 && groups_used < groups)) + } else { + most_used == 0 && groups == 0 + }; + if !fits { + return refuse(format!( + "its experts do not add up: {experts} experts, at most {most_used} used, {groups} groups of which {groups_used} used" + )); + } + match meta.int(&format!("{arch}.expert_gating_func"))? { + // `deepseek2` reads none as softmax; every other graph aborts on it + Some(0) if arch == "deepseek2" => Ok(()), + Some(1..=4) | None => Ok(()), + Some(other) => refuse(format!("its expert_gating_func is {other}, not 1 to 4")), + } +} + +/// The head counts: a graph divides by them, and attention needs whole +/// groups of query heads per KV head. +fn check_heads(meta: &Meta<'_>, arch: &str, layers: u64) -> Result<()> { + let heads = meta + .per_layer(&format!("{arch}.attention.head_count"))? + .unwrap_or_default(); + let kv_heads = meta + .per_layer(&format!("{arch}.attention.head_count_kv"))? + .unwrap_or_else(|| heads.clone()); + for (what, values) in [("head_count", &heads), ("head_count_kv", &kv_heads)] { + let too_long = values.len() > 1 && values.len() as u64 != layers; + if too_long || values.iter().any(|&n| n < 0 || n > i64::from(u32::MAX)) { + return refuse(format!("its attention.{what} {values:?} is out of range")); + } + } + let at = |values: &[i64], layer: usize| values.get(layer).or(values.first()).copied(); + for layer in 0..usize::try_from(layers)? { + if let (Some(q), Some(kv)) = (at(&heads, layer), at(&kv_heads, layer)) + && q > 0 + && kv > 0 + && q % kv != 0 + { + return refuse(format!( + "its layer {layer} has {q} query heads, not a whole number per each of its {kv} KV heads" + )); + } + } + if DIVIDES_BY_HEAD_COUNT.contains(&arch) && at(&heads, 0).unwrap_or(0) <= 0 { + return refuse(format!( + "its {arch} graph divides by the head count of layer 0, which is 0" + )); + } + Ok(()) +} + +/// The head width the rope rotates within: `key_length`, or the width per +/// head. +fn head_width(meta: &Meta<'_>, arch: &str) -> Result> { + if let Some(width) = meta.int(&format!("{arch}.attention.key_length"))? { + return Ok(Some(width)); + } + let embedding = meta.int(&format!("{arch}.embedding_length"))?; + let heads = meta.int(&format!("{arch}.attention.head_count"))?; + Ok(match (embedding, heads) { + (Some(embedding), Some(heads)) if heads > 0 => Some(embedding / heads), + _ => None, + }) +} + +/// The rope: an even number of rotated dimensions within a head, sections +/// that fit half a head, and a scaling type the loader knows. +fn check_rope(meta: &Meta<'_>, arch: &str) -> Result<()> { + if let Some(kind) = meta.optional_string(&format!("{arch}.rope.scaling.type"))? + && !ROPE_SCALING_TYPES.contains(&kind.as_str()) + { + return refuse(format!("its rope scaling type {kind:?} is unknown")); + } + let width = head_width(meta, arch)?; + for key in [ + format!("{arch}.rope.dimension_count"), + format!("{arch}.rope.dimension_count_swa"), + ] { + if let Some(rotated) = meta.int(&key)? { + let fits = width.is_none_or(|width| rotated <= width); + if !rotated.is_multiple_of(2) || !fits { + return refuse(format!( + "its {key} is {rotated}, not an even number within a head of {width:?}" + )); + } + } + } + let key = format!("{arch}.rope.dimension_sections"); + let sections = match meta.weights.arrays.get(&key) { + Some(MetaArray::Ints(sections)) => sections, + Some(MetaArray::Tokens(_)) => return refuse(format!("its {key} is not integers")), + None => return Ok(()), + }; + let sum = sections + .iter() + .try_fold(0i64, |sum, &s| (s >= 0).then(|| sum.saturating_add(s))); + let half = width.map(|width| i64::try_from(width / 2).unwrap_or(i64::MAX)); + match (sum, half) { + (Some(sum), Some(half)) if sum > 0 && sum <= half => Ok(()), + (Some(sum), None) if sum > 0 => Ok(()), + _ => refuse(format!( + "its rope sections {sections:?} do not fit half a head of {width:?}" + )), + } +} + +/// Options a graph aborts on when it does not know their value, and steps +/// and lengths it divides by or sizes from. +fn check_options(meta: &Meta<'_>, arch: &str) -> Result<()> { + if let Some(activation) = meta.optional_string(&format!("{arch}.classifier.activation"))? + && !CLASSIFIER_ACTIVATIONS.contains(&activation.as_str()) + { + return refuse(format!( + "its classifier activation {activation:?} is unknown" + )); + } + // a pooled model builds a pooling graph that aborts on an unknown kind, + // and is no chat model a receipt is for + match meta.int(&format!("{arch}.pooling_type"))? { + None | Some(0 | 0xffff_ffff) => {} + Some(kind) => return refuse(format!("it pools its output (pooling type {kind})")), + } + for key in [ + format!("{arch}.interleave_moe_layer_step"), + format!("{arch}.attention.indexer.top_k_frequency"), + ] { + if meta.int(&key)? == Some(0) { + return refuse(format!("its {key} is 0, which a graph divides by")); + } + } + if let Some(context) = meta.int(&format!("{arch}.context_length"))? + && (context == 0 || context > MAX_CONTEXT_LENGTH) + { + return refuse(format!( + "its context_length is {context}, not 1 to {MAX_CONTEXT_LENGTH}" + )); + } + // a norm's epsilon below zero, or not a number, fails a kernel's assert + for (key, value) in &meta.weights.metadata { + let is_epsilon = key.ends_with("epsilon") || key.ends_with("_eps") || key.ends_with(".eps"); + if let (true, MetaValue::Float(eps)) = (is_epsilon, value) + && !(eps.is_finite() && *eps >= 0.0) + { + return refuse(format!("its {key} is {eps}")); + } + } + Ok(()) +} + +/// The vocabulary: a tokenizer whose paths were checked, each token text +/// once, a token for every byte where the tokenizer falls back to bytes, +/// and an embedding row per token. +fn check_vocabulary(meta: &Meta<'_>) -> Result { + let model = meta.string("tokenizer.ggml.model")?; + if !TOKENIZERS.contains(&model.as_str()) { + return refuse(format!( + "its tokenizer {model:?} is not one this client checks before loading: {TOKENIZERS:?}" + )); + } + let tokens = meta.tokens()?; + if let Some(index) = tokens.duplicate { + return refuse(format!( + "its token {index} has the text of an earlier token" + )); + } + if model == "llama" && !tokens.has_every_byte() { + return refuse( + "its SentencePiece vocabulary has no token for some byte, which tokenizing falls back to", + ); + } + if let Ok(embedding) = meta.weights.tensor("token_embd.weight") + && embedding.rows() < tokens.count + { + return refuse(format!( + "its token embedding has {} rows for {} tokens", + embedding.rows(), + tokens.count + )); + } + Ok(tokens.count) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipt-audit/src/native_model/loader_asserts/tests.rs b/crates/skippy-receipt-audit/src/native_model/loader_asserts/tests.rs new file mode 100644 index 00000000..7b63bf55 --- /dev/null +++ b/crates/skippy-receipt-audit/src/native_model/loader_asserts/tests.rs @@ -0,0 +1,421 @@ +use anyhow::bail; +use skippy_receipts::weights::ByteSource; +use skippy_receipts::weights::limits::CannotAudit; + +use super::*; + +const UINT32: u32 = 4; +const INT32: u32 = 5; +const FLOAT32: u32 = 6; +const STRING: u32 = 8; +const ARRAY: u32 = 9; +const GGML_F32: u32 = 0; + +/// A metadata value of a test GGUF. +#[derive(Clone)] +enum Value { + U32(u32), + F32(f32), + Str(String), + Ints(Vec), + Strings(Vec>), +} + +struct Memory(Vec); + +impl ByteSource for Memory { + fn read_at(&self, offset: u64, len: u64) -> Result> { + let (start, end) = (offset as usize, (offset + len) as usize); + match self.0.get(start..end) { + Some(bytes) => Ok(bytes.to_vec()), + None => bail!("past the end"), + } + } + + fn size(&self) -> u64 { + self.0.len() as u64 + } +} + +fn string(out: &mut Vec, s: &[u8]) { + out.extend((s.len() as u64).to_le_bytes()); + out.extend(s); +} + +/// A GGUF of `metadata` and f32 `tensors` of the given shapes. +fn gguf(metadata: &[(String, Value)], tensors: &[(String, Vec)]) -> WeightFile { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend((tensors.len() as u64).to_le_bytes()); + out.extend((metadata.len() as u64).to_le_bytes()); + for (key, value) in metadata { + string(&mut out, key.as_bytes()); + match value { + Value::U32(v) => { + out.extend(UINT32.to_le_bytes()); + out.extend(v.to_le_bytes()); + } + Value::F32(v) => { + out.extend(FLOAT32.to_le_bytes()); + out.extend(v.to_le_bytes()); + } + Value::Str(v) => { + out.extend(STRING.to_le_bytes()); + string(&mut out, v.as_bytes()); + } + Value::Ints(values) => { + out.extend(ARRAY.to_le_bytes()); + out.extend(INT32.to_le_bytes()); + out.extend((values.len() as u64).to_le_bytes()); + for v in values { + out.extend(v.to_le_bytes()); + } + } + Value::Strings(values) => { + out.extend(ARRAY.to_le_bytes()); + out.extend(STRING.to_le_bytes()); + out.extend((values.len() as u64).to_le_bytes()); + for v in values { + string(&mut out, v); + } + } + } + } + let mut offset = 0u64; + for (name, dims) in tensors { + string(&mut out, name.as_bytes()); + out.extend((dims.len() as u32).to_le_bytes()); + for d in dims { + out.extend(d.to_le_bytes()); + } + out.extend(GGML_F32.to_le_bytes()); + out.extend(offset.to_le_bytes()); + offset += (dims.iter().product::() * 4).div_ceil(32) * 32; + } + out.resize(out.len().div_ceil(32) * 32 + offset as usize, 0); + WeightFile::open(Box::new(Memory(out))).expect("a test GGUF") +} + +/// A small model the loader takes: two layers, two query heads per KV +/// head, a byte-level vocabulary of three tokens. +struct Model { + metadata: Vec<(String, Value)>, + tensors: Vec<(String, Vec)>, +} + +impl Model { + fn new(arch: &str) -> Self { + let key = |k: &str| format!("{arch}.{k}"); + Self { + metadata: vec![ + ("general.architecture".into(), Value::Str(arch.into())), + (key("context_length"), Value::U32(4096)), + (key("embedding_length"), Value::U32(8)), + (key("block_count"), Value::U32(2)), + (key("attention.head_count"), Value::U32(2)), + (key("attention.head_count_kv"), Value::U32(1)), + (key("rope.dimension_count"), Value::U32(4)), + (key("attention.layer_norm_rms_epsilon"), Value::F32(1e-6)), + ("tokenizer.ggml.model".into(), Value::Str("gpt2".into())), + ( + "tokenizer.ggml.tokens".into(), + Value::Strings(vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]), + ), + ], + tensors: vec![("token_embd.weight".into(), vec![8, 3])], + } + } + + /// Sets `key` (under the architecture when it starts with `.`). + fn with(mut self, key: &str, value: Value) -> Self { + let key = match key.strip_prefix('.') { + Some(rest) => format!("{}.{rest}", self.arch()), + None => key.to_owned(), + }; + self.metadata.retain(|(k, _)| *k != key); + self.metadata.push((key, value)); + self + } + + fn tensor(mut self, name: &str, dims: Vec) -> Self { + self.tensors.retain(|(n, _)| n != name); + self.tensors.push((name.into(), dims)); + self + } + + fn arch(&self) -> String { + match &self.metadata[0].1 { + Value::Str(arch) => arch.clone(), + _ => unreachable!(), + } + } + + fn open(&self) -> WeightFile { + gguf(&self.metadata, &self.tensors) + } + + /// Why the checks refuse the model, which must be a [`CannotAudit`]. + fn refused(&self, what: &str) -> String { + let error = check(&self.open()) + .err() + .unwrap_or_else(|| panic!("{what} is not refused")); + assert!(CannotAudit::caused(&error), "{what}: {error:#}"); + error.to_string() + } +} + +fn byte_tokens() -> Vec> { + (0..=255u8) + .map(|b| format!("<0x{b:02X}>").into_bytes()) + .collect() +} + +#[test] +fn a_model_the_loader_takes_passes() { + assert_eq!(check(&Model::new("llama").open()).unwrap().vocabulary, 3); + // per-layer counts, rope sections and experts that add up + let model = Model::new("qwen3moe") + .with(".attention.head_count", Value::Ints(vec![2, 4])) + .with(".expert_count", Value::U32(8)) + .with(".expert_used_count", Value::Ints(vec![2, 2])) + .with(".rope.dimension_sections", Value::Ints(vec![1, 1, 0, 0])) + .with(".expert_gating_func", Value::U32(1)); + check(&model.open()).unwrap(); + let spm = Model::new("llama") + .with("tokenizer.ggml.model", Value::Str("llama".into())) + .with("tokenizer.ggml.tokens", Value::Strings(byte_tokens())) + .tensor("token_embd.weight", vec![8, 256]); + check(&spm.open()).unwrap(); +} + +/// Each value an assert or abort of the native code takes, refused before. +#[test] +fn the_values_the_native_code_asserts_on_are_refused() { + let llama = || Model::new("llama"); + let cases = [ + // llama-model.cpp, load_hparams + ("no layers", llama().with(".block_count", Value::U32(0))), + ("513 layers", llama().with(".block_count", Value::U32(513))), + ( + "-1 layers", + llama().with(".block_count", Value::U32(u32::MAX)), + ), + ( + "all next-token layers", + llama().with(".nextn_predict_layers", Value::U32(2)), + ), + ( + "a next-token layer without its tensors", + llama().with(".nextn_predict_layers", Value::U32(1)), + ), + ( + "an unknown classifier", + llama().with(".classifier.activation", Value::Str("relu6".into())), + ), + ( + "an unknown rope scaling", + llama().with(".rope.scaling.type", Value::Str("ntk".into())), + ), + ( + "too many experts", + llama() + .with(".expert_count", Value::U32(1025)) + .with(".expert_used_count", Value::U32(1)), + ), + ( + "more used than experts", + llama() + .with(".expert_count", Value::U32(4)) + .with(".expert_used_count", Value::U32(5)), + ), + ( + "experts none used", + llama().with(".expert_count", Value::U32(4)), + ), + ( + "used without experts", + llama().with(".expert_used_count", Value::U32(1)), + ), + ( + "a layer that uses more", + llama() + .with(".expert_count", Value::U32(4)) + .with(".expert_used_count", Value::Ints(vec![2, 5])), + ), + ( + "groups that do not divide", + llama() + .with(".expert_count", Value::U32(6)) + .with(".expert_used_count", Value::U32(1)) + .with(".expert_group_count", Value::U32(4)) + .with(".expert_group_used_count", Value::U32(1)), + ), + ( + "groups none used", + llama() + .with(".expert_count", Value::U32(8)) + .with(".expert_used_count", Value::U32(1)) + .with(".expert_group_count", Value::U32(4)), + ), + // llama-graph.cpp, the graph builders and the CPU kernels + ( + "an unknown gating", + llama() + .with(".expert_count", Value::U32(4)) + .with(".expert_used_count", Value::U32(1)) + .with(".expert_gating_func", Value::U32(9)), + ), + ( + "a pooled model", + llama().with(".pooling_type", Value::U32(7)), + ), + ( + "query heads not whole per KV head", + llama() + .with(".attention.head_count", Value::U32(3)) + .with(".attention.head_count_kv", Value::U32(2)), + ), + ( + "a layer's heads not whole", + llama() + .with(".attention.head_count", Value::Ints(vec![2, 3])) + .with(".attention.head_count_kv", Value::U32(2)), + ), + ( + "heads for more layers", + llama().with(".attention.head_count", Value::Ints(vec![2, 2, 2])), + ), + ( + "an odd rope", + llama().with(".rope.dimension_count", Value::U32(3)), + ), + ( + "a rope wider than a head", + llama().with(".rope.dimension_count", Value::U32(6)), + ), + ( + "no rope sections", + llama().with(".rope.dimension_sections", Value::Ints(vec![0, 0, 0, 0])), + ), + ( + "a negative rope section", + llama().with(".rope.dimension_sections", Value::Ints(vec![-2, 3, 0, 0])), + ), + ( + "rope sections past half a head", + llama().with(".rope.dimension_sections", Value::Ints(vec![2, 1, 0, 0])), + ), + ( + "an epsilon below zero", + llama().with(".attention.layer_norm_rms_epsilon", Value::F32(-1.0)), + ), + ( + "an epsilon that is no number", + llama().with(".attention.layer_norm_epsilon", Value::F32(f32::NAN)), + ), + ( + "a step of 0", + llama().with(".interleave_moe_layer_step", Value::U32(0)), + ), + ("no context", llama().with(".context_length", Value::U32(0))), + ( + "no heads in gemma2", + Model::new("gemma2") + .with(".attention.head_count", Value::U32(0)) + .with(".attention.head_count_kv", Value::U32(0)), + ), + ( + "all layers share a KV cache", + Model::new("gemma4").with(".attention.shared_kv_layers", Value::U32(1)), + ), + ( + "layers that read another's cache", + Model::new("mistral-large4"), + ), + // llama-vocab.cpp + ( + "no vocabulary", + llama().with("tokenizer.ggml.model", Value::Str("no_vocab".into())), + ), + ( + "a WordPiece vocabulary", + llama().with("tokenizer.ggml.model", Value::Str("bert".into())), + ), + ( + "a token twice", + llama().with( + "tokenizer.ggml.tokens", + Value::Strings(vec![b"a".to_vec(), b"b".to_vec(), b"a".to_vec()]), + ), + ), + ( + "an empty token named as another", + llama().with( + "tokenizer.ggml.tokens", + Value::Strings(vec![b"[EMPTY_1]".to_vec(), b"".to_vec(), b"c".to_vec()]), + ), + ), + ( + "a SentencePiece vocabulary short of a byte", + llama().with("tokenizer.ggml.model", Value::Str("llama".into())), + ), + ( + "fewer embedding rows than tokens", + llama().tensor("token_embd.weight", vec![8, 2]), + ), + ]; + for (what, model) in cases { + let why = model.refused(what); + assert!(!why.is_empty(), "{what}"); + } +} + +#[test] +fn the_values_a_model_may_have_pass() { + let llama = || Model::new("llama"); + for (what, model) in [ + ( + "an unspecified pooling", + llama().with(".pooling_type", Value::U32(u32::MAX)), + ), + ( + "deepseek2 reads no gating as softmax", + Model::new("deepseek2") + .with(".expert_count", Value::U32(4)) + .with(".expert_used_count", Value::U32(1)) + .with(".expert_gating_func", Value::U32(0)), + ), + ( + "a key length that sets the head", + llama() + .with(".attention.key_length", Value::U32(8)) + .with(".rope.dimension_count", Value::U32(8)), + ), + ( + "a next-token layer with its tensors", + llama() + .with(".nextn_predict_layers", Value::U32(1)) + .tensor("blk.1.nextn.eh_proj.weight", vec![8, 8]), + ), + ] { + if let Err(error) = check(&model.open()) { + panic!("{what}: {error:#}"); + } + } +} + +#[test] +fn a_layer_that_reads_another_layers_cache_is_not_loaded_alone() { + let gemma3n = Model::new("gemma3n") + .with(".block_count", Value::U32(30)) + .open(); + check_layer(&gemma3n, 19).unwrap(); + assert!(CannotAudit::caused(&check_layer(&gemma3n, 20).unwrap_err())); + let gemma4 = Model::new("gemma4") + .with(".block_count", Value::U32(30)) + .with(".attention.shared_kv_layers", Value::U32(10)) + .open(); + check_layer(&gemma4, 19).unwrap(); + assert!(check_layer(&gemma4, 20).is_err()); + check_layer(&Model::new("llama").open(), 1).unwrap(); +} diff --git a/crates/skippy-receipt-audit/src/node_text.rs b/crates/skippy-receipt-audit/src/node_text.rs new file mode 100644 index 00000000..29c9e6f9 --- /dev/null +++ b/crates/skippy-receipt-audit/src/node_text.rs @@ -0,0 +1,100 @@ +//! Text a node chose, made safe to print in a report. +//! +//! A receipt's id, model, backend, runtime and sampler, a tensor's name +//! and the response itself are whatever the node sent. Printed as they +//! are, a newline in one of them starts a line of the node's own, such as +//! `AUDIT PASS`, and an escape sequence rewrites the terminal. So a report +//! shows them on one line, with every control character written out. + +use std::fmt::Write; + +/// The most characters of one node-chosen text a report shows. +const SHOWN_CHARS: usize = 512; + +/// Whether a character moves the cursor, ends the line, or changes the +/// direction text is drawn in. +fn hidden(c: char) -> bool { + c.is_control() + || matches!( + c, + '\u{2028}' | '\u{2029}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' + ) +} + +/// `text` on one line: control characters, line separators and +/// bidirectional overrides are written as escapes, and a long text is cut. +pub(crate) fn shown(text: &str) -> String { + let mut out = String::with_capacity(text.len().min(SHOWN_CHARS)); + for (count, c) in text.chars().enumerate() { + if count == SHOWN_CHARS { + out.push('…'); + break; + } + match c { + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if hidden(c) => { + let _ = write!(out, "{}", c.escape_unicode()); + } + c => out.push(c), + } + } + out +} + +/// The first `chars` characters of `text`, shown: a hex root or key cut +/// for a report. Cuts between characters, wherever a byte count would fall. +pub(crate) fn short(text: &str, chars: usize) -> String { + let cut: String = text.chars().take(chars).collect(); + shown(&cut) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_node_cannot_write_a_line_of_its_own() { + let forged = "r1\nAUDIT PASS\r\n\x1b[2K\x1b[1Areceipt ok"; + let shown = shown(forged); + assert!(!shown.contains('\n') && !shown.contains('\r') && !shown.contains('\x1b')); + assert_eq!(shown, "r1\\nAUDIT PASS\\r\\n\\u{1b}[2K\\u{1b}[1Areceipt ok"); + // separators and overrides that draw as a line break or reorder it + for hidden in [ + '\u{2028}', '\u{2029}', '\u{202e}', '\u{2066}', '\u{0}', '\u{7f}', '\u{85}', + ] { + let text = format!("a{hidden}b"); + let shown = super::shown(&text); + assert!(!shown.contains(hidden), "{hidden:?} in {shown:?}"); + assert!( + shown.starts_with("a\\u{") && shown.ends_with('b'), + "{shown}" + ); + } + // ordinary text is left as it is + assert_eq!( + super::shown("Qwen3-4B Q8_0 / CUDA0 é 模型"), + "Qwen3-4B Q8_0 / CUDA0 é 模型" + ); + } + + #[test] + fn a_long_text_is_cut() { + let long = "x".repeat(10_000); + let shown = shown(&long); + assert_eq!(shown.chars().count(), SHOWN_CHARS + 1); + assert!(shown.ends_with('…')); + } + + #[test] + fn a_cut_falls_between_characters() { + // a byte slice at 16 would split the last character and panic + let root = "aéééééééé"; + assert!(!root.is_char_boundary(16)); + assert_eq!(short(root, 16), root); + assert_eq!(short("模型模型", 3), "模型模"); + assert_eq!(short("abc", 16), "abc"); + assert_eq!(short("ab\ncd", 4), "ab\\nc"); + } +} diff --git a/crates/skippy-receipt-audit/src/opening_checks.rs b/crates/skippy-receipt-audit/src/opening_checks.rs new file mode 100644 index 00000000..6695a534 --- /dev/null +++ b/crates/skippy-receipt-audit/src/opening_checks.rs @@ -0,0 +1,500 @@ +//! Every check that needs the opened values, on an opening that was +//! verified against the receipt and validated against the claimed model: +//! each picked layer's glue and weight rows, the input of layer 0, the +//! output head, the tokens, and the recurrent regions. An audit and a +//! recheck of its evidence share this. +//! +//! No check here stops the others. Each one's result is a verdict, a +//! defect of the opening, or a reason it could not run on this machine +//! ([`Check`]); the opening is already known to be whole, so what can still +//! stop a check is the client's own: a weight read, a layer that does not +//! load. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{Context, Result, anyhow}; +use skippy_receipts::attention::AttentionDescriptor; +use skippy_receipts::audit::{self, AuditReport, Routers}; +use skippy_receipts::cache_types; +use skippy_receipts::claimed_reads; +use skippy_receipts::glue::{self, GlueReport}; +use skippy_receipts::head::reasoning_budget::{self, Forcing, Vocabulary}; +use skippy_receipts::head::sampling::TokenRule; +use skippy_receipts::head::{self, HeadVerdict}; +use skippy_receipts::opened_values::ValidatedOpening; +use skippy_receipts::weights::WeightFile; +use skippy_receipts::wire::{LayerOpening, MixingKind}; + +use crate::chat_reply::ChatReply; +use crate::claimed_model::{CacheTypes, ClaimedModel}; +use crate::outcome::Check; +use crate::output::{ + AuditOutput, CostOutput, GlueOutput, HeadOutput, LayerOutput, MatrixOutput, ReasoningOutput, + RoleOutput, +}; +use crate::recurrent_audit::{self, KnownLayers}; +use crate::{head_key_file, token_check}; + +/// What the checks of an opening need beyond it. +pub(crate) struct Checks<'a> { + pub(crate) timing_runs: u32, + /// The prompt and the response, when the auditor received them. + pub(crate) response: Option<(&'a str, &'a ChatReply)>, + /// The client's head key file, which checks the node's logits. A + /// recheck has none, and checks them against every row of the output + /// matrix. + pub(crate) head_key: Option, +} + +/// Each picked layer's attention ops, as the auditor's graph describes +/// them, for the layers whose glue ran. +pub(crate) type Layouts = BTreeMap>; + +/// Runs every check of the opened values and records its result in +/// `output`. Returns the attention ops of the layers whose glue ran. +pub(crate) fn check_opening( + checks: &Checks<'_>, + model: &dyn ClaimedModel, + weights: &WeightFile, + opening: &ValidatedOpening<'_>, + rows_seed: &[u8], + output: &mut AuditOutput, +) -> Layouts { + let picks = &opening.challenge().picks; + // the layers load whole: what they read must be here first + let layers: Vec = picks.iter().map(|p| p.layer).collect(); + let fetched = claimed_reads::glue_ranges(weights, opening.opening(), &layers) + .and_then(|ranges| weights.prefetch(&ranges)) + .context("fetch the tensors the glue check reads"); + let mut reports = Vec::new(); + let mut layouts = Layouts::new(); + let mut state_layers = BTreeSet::new(); + for pick in picks { + let Some((layer, backend)) = opening.layer(pick.layer) else { + continue; + }; + let checked = match &fetched { + Ok(()) => check_layer( + checks.timing_runs, + model, + weights, + layer, + rows_seed, + backend, + ), + Err(error) => CheckedLayer::unavailable(layer, &format!("{error:#}")), + }; + output.layers.push(checked.output); + reports.extend(checked.rows); + if let Some(glue) = checked.glue { + layouts.insert(pick.layer, glue.attention); + if glue.states > 0 { + state_layers.insert(pick.layer); + } + } + } + output.roles = audit::pool_roles(&reports) + .iter() + .map(RoleOutput::from) + .collect(); + output.anchors = match &fetched { + Ok(()) => check_anchors(model, opening), + Err(error) => Check::Unavailable(format!("{error:#}")), + }; + output.head = check_head( + model, + weights, + opening, + checks.head_key.as_deref(), + rows_seed, + ); + note_unjudged_tokens(output); + output.tokens = checks.response.map(|(prompt, reply)| { + Check::of(token_check::check_tokens( + model, + opening.receipt(), + opening.prefix_tokens(), + prompt, + reply, + )) + }); + let evaluated: BTreeSet = layouts.keys().copied().collect(); + let known = KnownLayers { + evaluated: &evaluated, + state: &state_layers, + }; + output.recurrent = recurrent_audit::check_recurrent(model, opening, &known); + layouts +} + +/// A sampler statement that leaves the tokens unjudged is a gap of the +/// audit, which the report names. +fn note_unjudged_tokens(output: &mut AuditOutput) { + let Some(Check::Verdict(head)) = &output.head else { + return; + }; + if head.positions.iter().any(|p| !p.judged) { + output.notes.push(format!( + "not checked: the sampled tokens are {}; their logits were checked", + head.rule + )); + } +} + +/// The input of layer 0, recomputed from the receipt's tokens. +fn check_anchors(model: &dyn ClaimedModel, opening: &ValidatedOpening<'_>) -> Check { + let mut verdict = None; + let checked = model.with_layer(0, CacheTypes::default(), &mut |evaluator| { + verdict = Some(glue::check_anchors(evaluator, opening.anchors())?); + Ok(()) + }); + Check::of(checked.and_then(|()| { + let verdict = verdict.context("the anchors were not checked")?; + Ok(GlueOutput::from(&verdict)) + })) +} + +/// The sampled tokens at the head positions, judged on the logits the node +/// opened. An audit holds a head key and checks those logits with it. A +/// recheck has no key and checks them against every row of the claimed +/// output matrix. The two accept the same logits, so they give one +/// verdict. A node that left its logits out fails both. +/// +/// A model whose logits are not the output matrix's product is the +/// exception: its tokens are not judged, and its opened final residuals +/// are checked against the head alone. +/// +/// The key's refusal convinces no one else, since no one else has the +/// key. So when the key refuses some logits, the check reads every row as +/// a recheck does, and that verdict is the one reported: a recheck of the +/// evidence then reaches it too. +/// +/// A turn with a reasoning budget has tokens its sampler forced. The +/// check replays that sampler with the claimed model's tokenizer, so a +/// forced token must be the forced one and every other token is judged +/// as usual ([`reasoning_budget`]). +fn check_head( + model: &dyn ClaimedModel, + weights: &WeightFile, + opening: &ValidatedOpening<'_>, + head_key: Option<&Path>, + rows_seed: &[u8], +) -> Option> { + let (backend, openings) = opening.head()?; + if openings.is_empty() { + return None; + } + let receipt = opening.receipt(); + let started = Instant::now(); + let keyed = head_key.filter(|_| head::logits_are_linear(weights)); + let is_end = |token| model.is_end_of_generation(token); + let rule = head::token_rule_for(weights, receipt, &is_end); + let forcing = prefill_ends_the_prompt( + model, + opening, + reasoning_budget::replay(receipt, Some(&ClaimedVocabulary(model))), + ); + let every_row = || { + head::check_head( + weights, + receipt, + openings, + backend, + rows_seed, + (&rule, &forcing), + ) + }; + let checked: Result<(HeadVerdict, Option)> = match keyed { + Some(path) => head_key_file::load_or_build(path, weights).and_then(|(key, built)| { + let verdict = head::key::check_head_with_key( + weights, + &key, + receipt, + openings, + backend, + rows_seed, + (&rule, &forcing), + ); + // whether the key accepted the logits is a bit the node learns + // about it: a key that refused some is not used again + let refused = verdict.as_ref().is_ok_and(|v| { + v.positions + .iter() + .any(|p| p.logits.is_some_and(|l| !l.pass)) + }); + if !refused { + return Ok((verdict?, built)); + } + // a key that cannot be removed must not hide the verdict + let _ = head_key_file::discard(path); + // the check anyone can repeat; where it cannot run here, + // the key's verdict stands, and convinces this client alone + Ok((every_row().or(verdict)?, built)) + }), + None => every_row().map(|verdict| (verdict, None)), + }; + Some(Check::of(checked.map(|(verdict, built)| { + let seconds = started.elapsed().as_secs_f64() - built.unwrap_or(0.0); + let mut output = HeadOutput::new(&verdict, seconds); + output.rule = match forcing.unjudged() { + Some(reason) => TokenRule::Unjudged(reason.to_owned()).describe(), + None => rule.describe(), + }; + output.reasoning = ReasoningOutput::of(&forcing, &verdict); + output.key_build_seconds = built; + output + }))) +} + +/// `forcing`, unless the prefill its statement names is not the end of the +/// prompt: the sampler reads the prefill before the turn's tokens, so a +/// node that stated another one could choose which tokens it forced. Such +/// a turn's tokens are not judged. Whitespace is not compared, since the +/// template's text and the tokens' text may space it apart. +fn prefill_ends_the_prompt( + model: &dyn ClaimedModel, + opening: &ValidatedOpening<'_>, + forcing: Forcing, +) -> Forcing { + let Forcing::Replayed(replayed) = &forcing else { + return forcing; + }; + let unspaced = |text: &str| text.split_whitespace().collect::(); + let prefill = unspaced(&replayed.statement.prefill); + if prefill.is_empty() { + return forcing; + } + let receipt = opening.receipt(); + let split = receipt + .generation_start + .saturating_sub(receipt.position_start) as usize; + let turn = receipt.tokens.get(..split).unwrap_or(&receipt.tokens); + let prompt: Vec = opening + .prefix_tokens() + .iter() + .chain(turn) + .copied() + .collect(); + match model.detokenize(&prompt) { + Ok(text) if unspaced(&text).ends_with(&prefill) => forcing, + Ok(_) => Forcing::Unjudged( + "the prefill the reasoning budget names is not the end of the prompt".into(), + ), + Err(error) => Forcing::Unjudged(format!( + "the claimed model cannot turn the prompt into text: {error:#}" + )), + } +} + +/// The claimed model's tokenizer, for the replay of a reasoning budget. +struct ClaimedVocabulary<'a>(&'a dyn ClaimedModel); + +impl Vocabulary for ClaimedVocabulary<'_> { + fn tokenize(&self, text: &str) -> Result> { + self.0.tokenize(text) + } + + fn piece(&self, token: i32) -> Result> { + self.0.token_piece(token) + } +} + +/// One picked layer, checked. +struct CheckedLayer { + output: LayerOutput, + /// The row check's report, when it ran. + rows: Option, + /// The glue check's report, when it ran. + glue: Option, +} + +impl CheckedLayer { + /// A layer no check of which could run here. + fn unavailable(opening: &LayerOpening, reason: &str) -> Self { + Self { + output: LayerOutput { + layer: opening.layer, + matrices: Vec::new(), + rows_fault: None, + rows_error: Some(reason.to_owned()), + glue: Vec::new(), + glue_pass: false, + glue_fault: None, + glue_error: Some(reason.to_owned()), + unchecked_weights: Vec::new(), + cost: CostOutput { + positions: opening.leaves.len(), + ..CostOutput::default() + }, + }, + rows: None, + glue: None, + } + } +} + +/// The glue check on the layer loaded alone, then the row checks. The +/// glue's evaluation gives the layer's plan: which weight each matmul +/// reads and which are routers. The row check takes those from it, never +/// from the opening; where the glue could not run it takes no matmul for +/// a router. +fn check_layer( + timing_runs: u32, + model: &dyn ClaimedModel, + weights: &WeightFile, + opening: &LayerOpening, + rows_seed: &[u8], + backend: &str, +) -> CheckedLayer { + let started = Instant::now(); + let mut glue_eval_seconds = Vec::new(); + let mut glue_check_seconds = 0.0; + let mut report = None; + let loaded = model.with_layer( + opening.layer, + layer_cache_types(opening), + &mut |evaluator| { + let check_started = Instant::now(); + let checked = glue::check_glue(evaluator, opening)?; + glue_check_seconds = check_started.elapsed().as_secs_f64(); + glue_eval_seconds.push(checked.eval_seconds); + let request = glue::glue_request(opening)?; + for _ in 1..timing_runs { + let run_started = Instant::now(); + evaluator.evaluate(&request)?; + glue_eval_seconds.push(run_started.elapsed().as_secs_f64()); + } + report = Some(checked); + Ok(()) + }, + ); + let layer_seconds = started.elapsed().as_secs_f64(); + let glue: Check = + Check::of(loaded.and_then(|()| report.ok_or_else(|| anyhow!("the glue was not checked")))); + let started = Instant::now(); + let check_rows = |routers| audit::check_rows(weights, opening, routers, rows_seed, backend); + let rows: Check = match &glue { + Check::Verdict(glue) => Check::of(check_rows(Routers::Planned(&glue.matmuls))), + Check::NodeFault(_) => Check::Unavailable( + "not checked: the glue check found the opening of the layer defective".to_owned(), + ), + // without the layer's plan no matmul is known for a router: each + // is checked on a sample of its rows. A column that fails is still + // a failure, and the glue that could not run keeps the layer from + // counting as checked. + Check::Unavailable(_) => Check::of(check_rows(Routers::Unknown)), + }; + let row_check_seconds = started.elapsed().as_secs_f64(); + let glue_seconds: f64 = glue_check_seconds + glue_eval_seconds.iter().skip(1).sum::(); + let ran = glue.verdict(); + let output = LayerOutput { + layer: opening.layer, + matrices: rows + .verdict() + .map(|r| r.matrices.iter().map(MatrixOutput::from).collect()) + .unwrap_or_default(), + rows_fault: rows.node_fault().map(str::to_owned), + rows_error: rows.unavailable().map(str::to_owned), + glue: ran + .map(|g| g.verdicts.iter().map(GlueOutput::from).collect()) + .unwrap_or_default(), + glue_pass: ran.is_some_and(|g| g.pass), + glue_fault: glue.node_fault().map(str::to_owned), + glue_error: glue.unavailable().map(str::to_owned), + unchecked_weights: ran.map(|g| g.unchecked_weights.clone()).unwrap_or_default(), + cost: CostOutput { + positions: opening.leaves.len(), + layer_load_seconds: (layer_seconds - glue_seconds).max(0.0), + glue_eval_seconds, + glue_check_seconds, + row_check_seconds, + }, + }; + CheckedLayer { + output, + rows: match rows { + Check::Verdict(report) => Some(report), + _ => None, + }, + glue: match glue { + Check::Verdict(report) => Some(report), + _ => None, + }, + } +} + +/// The KV cache types of the rows `opening`'s layer stored: its first +/// stored row is the key, its second the value. The auditor builds its +/// layer with them, so they reach the native runtime: only a type the +/// auditor checks is taken from the opening, and any other keeps the +/// default. +fn layer_cache_types(opening: &LayerOpening) -> CacheTypes { + let stored = |index| { + opening + .leaves + .iter() + .flat_map(|leaf| &leaf.mixing) + .find(|m| m.kind == MixingKind::Stored && m.index == index && m.values.is_some()) + .and_then(|m| cache_types::audited(m.ggml_type)) + }; + let k = stored(0); + CacheTypes { + k, + v: stored(1).or(k), + } +} + +#[cfg(test)] +mod tests { + use skippy_receipts::wire::{LeafOpening, TensorOpening}; + + use super::*; + + fn layer(stored: &[(u32, i32)]) -> LayerOpening { + let mixing = stored + .iter() + .map(|&(index, ggml_type)| { + TensorOpening::new(MixingKind::Stored, index, Some((ggml_type, &[0u8; 4]))) + }) + .collect(); + LayerOpening { + layer: 3, + leaves: vec![LeafOpening { + position: 0, + residual_in: String::new(), + residual_out: None, + residual_in_path: Vec::new(), + mixing_path: Vec::new(), + residual_out_path: Vec::new(), + mixing, + matrices: Vec::new(), + selections: Vec::new(), + }], + } + } + + #[test] + fn only_a_cache_type_an_audit_covers_reaches_the_layer_load() { + // f16 keys and f32 values + let types = layer_cache_types(&layer(&[(0, 1), (1, 0)])); + assert_eq!((types.k, types.v), (Some(1), Some(0))); + // one stored row: the value has the key's type + let types = layer_cache_types(&layer(&[(0, 1)])); + assert_eq!((types.k, types.v), (Some(1), Some(1))); + // no audit covers a quantized cache (q8_0 is 8, q4_0 is 2), so its + // types never reach the load + for quantized in [8, 2] { + let types = layer_cache_types(&layer(&[(0, quantized), (1, quantized)])); + assert_eq!(types, CacheTypes::default(), "{quantized}"); + } + // 39 is no ggml type, and a negative id is none either: llama.cpp + // would abort on them, so the load keeps its default + for unknown in [39, 3, -1, i32::MAX] { + let types = layer_cache_types(&layer(&[(0, unknown), (1, unknown)])); + assert_eq!(types, CacheTypes::default(), "{unknown}"); + } + assert_eq!(layer_cache_types(&layer(&[])), CacheTypes::default()); + } +} diff --git a/crates/skippy-receipt-audit/src/outcome.rs b/crates/skippy-receipt-audit/src/outcome.rs new file mode 100644 index 00000000..d39ce529 --- /dev/null +++ b/crates/skippy-receipt-audit/src/outcome.rs @@ -0,0 +1,169 @@ +//! What an audit says about a node, and what one check of it found. +//! +//! An audit ends one of four ways, and a caller must be able to tell them +//! apart, because they call for different things: +//! +//! - **pass:** every check ran and held. +//! - **fail:** the node's receipt or answer is defective, or contradicts +//! what the client sent or received. A failure is *provable* when it +//! lies in something the node signed, so anyone can be shown it: the +//! receipt, or an answer kept as evidence. It is not when only this +//! client can see it: the response text, the request. +//! - **unanswered:** the node gave no usable signed answer to the +//! challenge. Nothing was checked, and that is the node's doing. +//! - **no audit:** the client could not run a check. That says nothing +//! about the node. +//! +//! A check that stops with an error is sorted by the mark the error +//! carries ([`skippy_receipts::node_fault`]), never by its text. + +use serde::Serialize; +use skippy_receipts::node_fault::NodeFault; + +/// How an audit of a turn ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Pass, + Fail, + NoAudit, + Unanswered, +} + +impl Outcome { + /// The exit code of `skippy audit-receipt` and `skippy recheck-receipt`. + pub fn exit_code(self) -> u8 { + match self { + Self::Pass => 0, + Self::Fail => 1, + Self::NoAudit => 2, + Self::Unanswered => 3, + } + } + + /// The last line of a text report. + pub fn line(self) -> &'static str { + match self { + Self::Pass => "AUDIT PASS", + Self::Fail => "AUDIT FAIL", + Self::NoAudit => "NO AUDIT", + Self::Unanswered => "NO ANSWER", + } + } +} + +/// What one check of an audit found. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Check { + /// The check ran: its verdict. + Verdict(T), + /// The node's answer is defective: a failure, whatever a verdict would + /// have been. + NodeFault(String), + /// The check could not run here, which says nothing about the node. + Unavailable(String), +} + +impl Check { + /// Sorts the result of a check: a verdict, an error that blames the + /// node, or any other error, which is the client's. + pub fn of(result: anyhow::Result) -> Self { + match result { + Ok(verdict) => Self::Verdict(verdict), + Err(error) if NodeFault::find(&error).is_some() => { + Self::NodeFault(format!("{error:#}")) + } + Err(error) => Self::Unavailable(format!("{error:#}")), + } + } + + pub fn verdict(&self) -> Option<&T> { + match self { + Self::Verdict(verdict) => Some(verdict), + _ => None, + } + } + + pub fn node_fault(&self) -> Option<&str> { + match self { + Self::NodeFault(reason) => Some(reason), + _ => None, + } + } + + pub fn unavailable(&self) -> Option<&str> { + match self { + Self::Unavailable(reason) => Some(reason), + _ => None, + } + } +} + +/// A check that failed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Failure { + /// The check, and why it failed, in a few words. + pub check: String, + /// The failure lies in something the node signed, so anyone can be + /// shown it: the receipt, or an answer the audit keeps as evidence, + /// which `skippy recheck-receipt` fails the same way. + pub provable: bool, +} + +impl Failure { + pub(crate) fn provable(check: impl Into) -> Self { + Self { + check: check.into(), + provable: true, + } + } + + pub(crate) fn unprovable(check: impl Into) -> Self { + Self { + check: check.into(), + provable: false, + } + } +} + +#[cfg(test)] +mod tests { + use skippy_receipts::node_fault::NodeFault; + + use super::*; + + #[test] + fn each_outcome_has_its_exit_code_line_and_name() { + let expected = [ + (Outcome::Pass, 0, "AUDIT PASS", "\"pass\""), + (Outcome::Fail, 1, "AUDIT FAIL", "\"fail\""), + (Outcome::NoAudit, 2, "NO AUDIT", "\"no_audit\""), + (Outcome::Unanswered, 3, "NO ANSWER", "\"unanswered\""), + ]; + for (outcome, code, line, name) in expected { + assert_eq!(outcome.exit_code(), code); + assert_eq!(outcome.line(), line); + assert_eq!(serde_json::to_string(&outcome).unwrap(), name); + } + } + + #[test] + fn an_error_is_sorted_by_its_mark() { + let fault: Check = Check::of(Err(NodeFault::error("a short column"))); + assert_eq!(fault.node_fault(), Some("a short column")); + // an error nobody marked is the client's: it could not run the check + let read: anyhow::Result = Err(anyhow::anyhow!("connection reset")); + let unmarked = Check::of(read.map_err(|e| e.context("fetch a weight row"))); + assert_eq!( + unmarked.unavailable(), + Some("fetch a weight row: connection reset") + ); + assert_eq!(Check::of(Ok(3u8)).verdict(), Some(&3)); + // the three serialize apart + let json = |check: &Check| serde_json::to_string(check).unwrap(); + assert_eq!(json(&Check::Verdict(1)), r#"{"verdict":1}"#); + assert_eq!(json(&fault), r#"{"node_fault":"a short column"}"#); + assert!(json(&unmarked).starts_with(r#"{"unavailable":"#)); + } +} diff --git a/crates/skippy-receipt-audit/src/output.rs b/crates/skippy-receipt-audit/src/output.rs new file mode 100644 index 00000000..16af386a --- /dev/null +++ b/crates/skippy-receipt-audit/src/output.rs @@ -0,0 +1,699 @@ +//! What an audit of a turn reports: every check's result, and what they +//! add up to. `skippy audit-receipt` prints it as JSON, or as text +//! ([`crate::report_text`]). + +use serde::Serialize; +use skippy_receipts::audit::{MatrixVerdict, RoleVerdict}; +use skippy_receipts::glue::GlueVerdict; +use skippy_receipts::head::reasoning_budget::Forcing; +use skippy_receipts::head::{HeadVerdict, PositionVerdict}; +use skippy_receipts::wire::{Challenge, Receipt}; + +use crate::attention_audit::AttentionOutput; +use crate::outcome::{Check, Failure, Outcome}; +use crate::recurrent_audit::{self, RecurrentOutput}; + +#[derive(Serialize)] +pub struct AuditOutput { + /// What the checks add up to: `pass`, `fail`, `no_audit` when a check + /// could not run here, or `unanswered` when the node did not open the + /// attention rows. + pub outcome: Outcome, + /// Whether the outcome is `pass`. + pub pass: bool, + /// The checks that failed, and whether the evidence shows each. + pub failures: Vec, + /// The checks that could not run here, and why: they say nothing about + /// the node. + pub unchecked: Vec, + /// What the audit does not cover for this turn: neither a pass nor a + /// failure. + pub notes: Vec, + pub response: String, + pub receipt: Receipt, + pub challenge: Challenge, + /// Why the receipt is not one this client can hold the node to: it is + /// not bound to the client's key and signed by the node. A failure + /// only this client can see. + pub binding_error: Option, + /// Why the receipt the node signed does not describe a turn of the + /// claimed model: its stages, positions, tokens or cached prefix. The + /// signed receipt shows this failure to anyone. An audit that refuses + /// a receipt sends no challenge, so it keeps no evidence file. + pub receipt_error: Option, + /// Why the opening the node signed is defective: it is not the answer + /// to the challenge, a leaf is not in its tree, or a value does not fit + /// the claimed model. A failure the evidence shows. + pub opening_error: Option, + /// How the receipt contradicts the request the client sent: its id or + /// its sampler statement. A failure no evidence shows, since the + /// request is not part of a receipt. + pub request_errors: Vec, + pub layers: Vec, + /// The row fail rule, per weight role across the opened layers. + pub roles: Vec, + /// The input of layer 0 against the receipt's tokens. + pub anchors: Check, + /// The sampled tokens against the output head. Absent when the turn + /// sampled no token from a position it computed. + pub head: Option>, + /// The response against the sampled tokens. Absent when rechecking + /// evidence: the node does not sign the response. + pub tokens: Option>, + /// Hex VRF proof of the rows checked, from the opening as received. + pub rows_proof: Option, + /// The attention of the picked heads. Absent when it did not run. + pub attention: Option, + /// The recurrent token mixing of each stage's first attention pick on + /// a layer that keeps a recurrent state. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub recurrent: Vec, + /// The challenge was picked by hand (`--layer`), not drawn from the VRF. + pub hand_picked: bool, + /// Seconds from sending the challenge to receiving the whole opening. + /// The node is meant to answer within the 10-second challenge window. + pub open_seconds: Option, +} + +impl AuditOutput { + pub(crate) fn new(response: String, receipt: Receipt, challenge: Challenge) -> Self { + Self { + outcome: Outcome::NoAudit, + pass: false, + failures: Vec::new(), + unchecked: Vec::new(), + notes: Vec::new(), + response, + receipt, + challenge, + binding_error: None, + receipt_error: None, + opening_error: None, + request_errors: Vec::new(), + layers: Vec::new(), + roles: Vec::new(), + anchors: Check::Unavailable("not checked".to_owned()), + head: None, + tokens: None, + rows_proof: None, + attention: None, + recurrent: Vec::new(), + hand_picked: false, + open_seconds: None, + } + } + + /// Whether the checks of the opened values ran: they do not when the + /// receipt or the opening is refused. + pub(crate) fn opened(&self) -> bool { + self.binding_error.is_none() && self.receipt_error.is_none() && self.opening_error.is_none() + } + + /// Adds the checks up. A failure decides the outcome whatever else + /// happened; a node that then did not open the attention rows left the + /// audit unanswered; a check that could not run makes it no audit. + pub(crate) fn finish(&mut self) { + self.failures = self.collect_failures(); + self.unchecked = self.collect_unchecked(); + let unanswered = self + .attention + .as_ref() + .is_some_and(|a| a.rows_unanswered.is_some()); + self.outcome = if !self.failures.is_empty() { + Outcome::Fail + } else if unanswered { + Outcome::Unanswered + } else if !self.unchecked.is_empty() { + Outcome::NoAudit + } else { + Outcome::Pass + }; + self.pass = self.outcome == Outcome::Pass; + } + + /// The checks that failed, in a few words each: what + /// [`Self::failures`] holds once the audit is finished. + pub fn failures(&self) -> Vec { + self.failures.iter().map(|f| f.check.clone()).collect() + } + + /// The checks that could not run here, and why. + pub fn unchecked(&self) -> Vec { + self.unchecked.clone() + } + + /// Whether the evidence shows a failure: `skippy recheck-receipt` + /// fails too. + pub fn provable(&self) -> bool { + self.failures.iter().any(|f| f.provable) + } + + fn collect_failures(&self) -> Vec { + let mut out = Vec::new(); + if let Some(error) = &self.binding_error { + out.push(Failure::unprovable(format!("binding: {error}"))); + } + if let Some(error) = &self.receipt_error { + out.push(Failure::provable(format!("receipt: {error}"))); + } + out.extend( + self.request_errors + .iter() + .map(|error| Failure::unprovable(format!("request: {error}"))), + ); + if let Some(error) = &self.opening_error { + out.push(Failure::provable(format!("opening: {error}"))); + } + if !self.opened() { + return out; + } + out.extend(self.roles.iter().filter(|r| !r.pass).map(|r| { + Failure::provable(format!( + "weight rows of {}: {}/{} fail, {} past the cap", + r.role, r.failing_tokens, r.tokens, r.past_cap + )) + })); + for layer in &self.layers { + out.extend(layer.failures().into_iter().map(Failure::provable)); + } + match &self.anchors { + Check::Verdict(anchors) if !anchors.pass => { + out.push(Failure::provable("input of layer 0")); + } + Check::NodeFault(fault) => { + out.push(Failure::provable(format!("input of layer 0: {fault}"))); + } + _ => {} + } + out.extend(self.head_failure()); + if let Some(attention) = &self.attention { + out.extend(attention.failures().into_iter().map(Failure::provable)); + } + out.extend( + recurrent_audit::failures(&self.recurrent) + .into_iter() + .map(Failure::provable), + ); + out.extend(self.token_failures()); + out + } + + /// The evidence shows a token the node's own logits do not give, and + /// logits that a check of every row of the output matrix refused, + /// which anyone repeats. Logits that only the client's key check + /// refused convince nobody who lacks the key. A recheck of the + /// evidence checks every row, and shows them when they are that far + /// off. + fn head_failure(&self) -> Option { + match self.head.as_ref()? { + Check::Verdict(head) if !head.pass => Some(Failure { + check: "output head".to_owned(), + provable: head + .positions + .iter() + .any(|p| !p.pass && !p.refused_by_the_key_alone()), + }), + // a recheck reads the same opening and finds the same defect + Check::NodeFault(fault) => Some(Failure::provable(format!("output head: {fault}"))), + _ => None, + } + } + + /// The node does not sign the response, and the request is not part of + /// a receipt: these convince only the client that saw both. + fn token_failures(&self) -> Vec { + let mut out = Vec::new(); + match &self.tokens { + Some(Check::Verdict(tokens)) => { + if !tokens.response_ok { + out.push(Failure::unprovable("response against the sampled tokens")); + } + if !tokens.prompt_ok { + out.push(Failure::unprovable("prompt against the receipt's tokens")); + } + } + Some(Check::NodeFault(fault)) => { + out.push(Failure::unprovable(format!("tokens: {fault}"))); + } + _ => {} + } + out + } + + fn collect_unchecked(&self) -> Vec { + if !self.opened() { + return Vec::new(); + } + let mut out: Vec = self + .layers + .iter() + .flat_map(LayerOutput::unchecked) + .collect(); + if self.layers.len() != self.challenge.picks.len() { + out.push("picked layers: not every one was checked".to_owned()); + } + if let Some(reason) = self.anchors.unavailable() { + out.push(format!("input of layer 0: {reason}")); + } + match &self.head { + Some(head) => out.extend( + head.unavailable() + .map(|reason| format!("output head: {reason}")), + ), + None if !self.challenge.head.is_empty() => { + out.push("output head: not checked".to_owned()); + } + None => {} + } + match &self.attention { + Some(attention) => out.extend(attention.unchecked()), + None if !self.challenge.attention.is_empty() => { + out.push("attention: not checked".to_owned()); + } + None => {} + } + out.extend(recurrent_audit::unchecked(&self.recurrent)); + if let Some(reason) = self.tokens.as_ref().and_then(Check::unavailable) { + out.push(format!("tokens: {reason}")); + } + out + } + + /// The report `skippy audit-receipt` prints. + pub fn render_text(&self) -> String { + let mut out = Vec::new(); + let _ = crate::report_text::render(&mut out, self); + String::from_utf8_lossy(&out).into_owned() + } +} + +/// A receipt this verifier cannot audit, and why. It is no audit, not a +/// failed one ([`skippy_receipts::coverage`]). +#[derive(Serialize)] +pub struct NoAuditOutput { + pub outcome: Outcome, + pub pass: bool, + pub receipt_id: String, + pub reason: String, +} + +impl NoAuditOutput { + pub fn new(receipt_id: impl Into, reason: impl Into) -> Self { + Self { + outcome: Outcome::NoAudit, + pass: false, + receipt_id: receipt_id.into(), + reason: reason.into(), + } + } +} + +/// A challenge the node gave no usable signed answer to: nothing was +/// checked, and that is the node's doing. Neither a pass, a failure nor no +/// audit. +#[derive(Serialize)] +pub struct UnansweredOutput { + pub outcome: Outcome, + pub pass: bool, + pub receipt_id: String, + /// What the node did not answer: `open` for the challenge, `rows` for + /// the attention rows. + pub request: &'static str, + pub reason: String, +} + +impl UnansweredOutput { + pub(crate) fn new( + receipt_id: impl Into, + request: &'static str, + reason: impl Into, + ) -> Self { + Self { + outcome: Outcome::Unanswered, + pass: false, + receipt_id: receipt_id.into(), + request, + reason: reason.into(), + } + } +} + +#[derive(Serialize)] +pub struct HeadOutput { + pub positions: Vec, + /// Tokens accepted only within the tie band. + pub ties: usize, + /// Draws that pick the sampled token only within the band. + pub band_draws: usize, + pub flagged: bool, + pub pass: bool, + /// Checking the node's logits with the client's head key, or, without + /// one, reading the output matrix and checking them on every row. + pub seconds: f64, + /// The node's logits were checked with the client's head key. + pub keyed: bool, + /// The node's logits were checked against every row of the output + /// matrix, with no key. + pub every_row: bool, + /// Building the head key, when this audit built it. + pub key_build_seconds: Option, + /// How the tokens were judged: the greedy choice, kept by the turn's + /// sampler, or not judged and why. + pub rule: String, + /// The reasoning budget of the turn, when the node states the sampler + /// that enforces it and the check replayed it. + pub reasoning: Option, +} + +/// The reasoning-budget sampler of a turn, as the node states it, and what +/// its replay found. The tags are the node's words: a client that knows +/// the model's chat template can compare them with it. +#[derive(Serialize)] +pub struct ReasoningOutput { + /// The tokens of reasoning the sampler allows. + pub budget: i32, + /// The tag that starts the reasoning. + pub start: String, + /// The tags that end it. The sampler forces the first when the budget + /// runs out. + pub ends: Vec, + /// The text the chat template placed after the prompt. + pub prefill: String, + /// The head positions whose token the sampler forced. + pub forced: usize, +} + +impl ReasoningOutput { + /// The replayed sampler of `forcing`, with the forced tokens among the + /// positions of `verdict`. + pub(crate) fn of(forcing: &Forcing, verdict: &HeadVerdict) -> Option { + let Forcing::Replayed(replayed) = forcing else { + return None; + }; + let statement = &replayed.statement; + Some(Self { + budget: statement.budget, + start: statement.start.clone(), + ends: statement.ends.clone(), + prefill: statement.prefill.clone(), + forced: verdict + .positions + .iter() + .filter(|p| p.forced.is_some()) + .count(), + }) + } +} + +#[derive(Serialize)] +pub struct HeadPositionOutput { + pub position: u32, + pub sampled: i32, + pub best: i32, + pub margin: f64, + pub band: f64, + pub within_band: bool, + /// The sampler let the check judge the token. + pub judged: bool, + /// How far under its tolerance the key check's error was, in powers of + /// ten (below 0 over it), when the node's logits were checked with the + /// head key ([`skippy_receipts::head::key::key_margin`]). The error + /// itself is never shown: it says something of the secret key. + pub key_margin: Option, + /// The error of the node's logits over every row of the output matrix, + /// relative to their norm, when they were checked without a key. + pub every_row_error: Option, + /// The row check's error, when the node's logits were checked. + pub row_error: Option, + /// Whether the node's logits passed their check, when one ran. + pub logits_ok: Option, + /// Roundings of the activation the node took the other way, which + /// the check of its logits allowed for. + pub rounding_flips: Option, + /// The replay of the draw that picked the token, when the turn's + /// sampler statement lets the check replay it. + pub draw: Option, + /// The token the turn's reasoning budget forced here, when it forced + /// one: the sampled token must be it. + pub forced: Option, + /// The token passed its judgement on the logits the node opened. + pub token_ok: bool, + pub pass: bool, +} + +/// One replayed draw: the uniform of the seed and the position, and the +/// uniforms that pick the sampled token at the widest the band allows. +#[derive(Serialize)] +pub struct DrawOutput { + pub uniform: f64, + pub lower: f64, + pub upper: f64, + /// The uniform picks the token without the band's help. + pub exact: bool, + pub pass: bool, +} + +impl DrawOutput { + /// The draw does not pick the token the node sampled. + pub(crate) fn failed(&self) -> bool { + !self.pass + } +} + +impl HeadPositionOutput { + /// The check of the node's logits refused them. + pub(crate) fn logits_failed(&self) -> bool { + self.logits_ok == Some(false) + } + + /// Only the client's key refused the node's logits: no check of every + /// row did, and the token passed on the logits the node opened. + fn refused_by_the_key_alone(&self) -> bool { + self.logits_failed() && self.key_margin.is_some() && self.token_ok + } +} + +/// Whether the logits of every position were checked: against every row +/// of the output matrix when `every_row`, else with a head key. +fn checked(verdict: &HeadVerdict, every_row: bool) -> bool { + verdict + .positions + .iter() + .all(|p| p.logits.is_some_and(|l| l.every_row == every_row)) +} + +impl HeadOutput { + pub(crate) fn new(verdict: &HeadVerdict, seconds: f64) -> Self { + let position = |p: &PositionVerdict| HeadPositionOutput { + position: p.position, + sampled: p.sampled, + best: p.best, + margin: p.margin, + band: p.band, + within_band: p.within_band, + judged: p.judged, + key_margin: p + .logits + .filter(|l| !l.every_row) + .map(|l| skippy_receipts::head::key::key_margin(l.error)), + every_row_error: p.logits.filter(|l| l.every_row).map(|l| l.error), + row_error: p.logits.map(|l| l.row_error), + logits_ok: p.logits.map(|l| l.pass), + rounding_flips: p.logits.map(|l| l.rounding_flips), + draw: p.draw.map(|d| DrawOutput { + uniform: d.uniform, + lower: d.lower, + upper: d.upper, + exact: d.exact, + pass: d.pass, + }), + forced: p.forced, + token_ok: p.token_pass, + pass: p.pass, + }; + Self { + positions: verdict.positions.iter().map(position).collect(), + ties: verdict.ties, + band_draws: verdict.band_draws, + flagged: verdict.flagged, + pass: verdict.pass, + seconds, + keyed: checked(verdict, false), + every_row: checked(verdict, true), + key_build_seconds: None, + rule: String::new(), + reasoning: None, + } + } +} + +#[derive(Serialize)] +pub struct LayerOutput { + pub layer: u32, + pub matrices: Vec, + /// Why the row check found the opening defective: a failure. + pub rows_fault: Option, + /// Why the rows could not be checked here. + pub rows_error: Option, + pub glue: Vec, + pub glue_pass: bool, + /// Why the glue check found the opening defective: a failure. + pub glue_fault: Option, + /// Why the glue could not be checked here. + pub glue_error: Option, + /// Weights read inside token-mixing ops, which no check covers. + pub unchecked_weights: Vec, + pub cost: CostOutput, +} + +impl LayerOutput { + /// The layer's failures: a defect of its opening, or a glue comparison + /// that does not hold. Row failures are judged per role, over every + /// opened layer. + fn failures(&self) -> Vec { + let mut out = Vec::new(); + if let Some(fault) = &self.rows_fault { + out.push(format!("weight rows of layer {}: {fault}", self.layer)); + } + match &self.glue_fault { + Some(fault) => out.push(format!("glue of layer {}: {fault}", self.layer)), + None if self.glue_error.is_none() && !self.glue_pass => { + out.push(format!("glue of layer {}", self.layer)); + } + None => {} + } + out + } + + fn unchecked(&self) -> Vec { + let mut out = Vec::new(); + if let Some(reason) = &self.glue_error { + out.push(format!("glue of layer {}: {reason}", self.layer)); + } + if let Some(reason) = &self.rows_error { + out.push(format!("weight rows of layer {}: {reason}", self.layer)); + } + out + } +} + +#[derive(Serialize)] +pub struct RoleOutput { + pub role: String, + pub layers: Vec, + pub router: bool, + pub tokens: usize, + pub failing_tokens: usize, + /// Failing columns past the cap, each of which fails the role. + pub past_cap: usize, + pub pass: bool, +} + +impl From<&RoleVerdict> for RoleOutput { + fn from(r: &RoleVerdict) -> Self { + Self { + role: r.role.clone(), + layers: r.layers.clone(), + router: r.router, + tokens: r.tokens, + failing_tokens: r.failing_tokens, + past_cap: r.past_cap, + pass: r.pass, + } + } +} + +#[derive(Serialize)] +pub struct TokenOutput { + /// The text of the sampled tokens. + pub generated: String, + pub response_ok: bool, + /// Whether the client's message is in the text of the tokens before + /// the sampled ones where an honest node puts it ([`Self::prompt_compared`]). + pub prompt_ok: bool, + /// What the prompt check compared: where the message was found, if at + /// all. The rest of the prompt is not compared. + pub prompt_compared: String, +} + +#[derive(Serialize)] +pub struct GlueOutput { + pub check: String, + pub tokens: usize, + pub failing_tokens: usize, + pub max_error: f64, + pub worst: String, + pub failures: Vec, + pub pass: bool, +} + +impl From<&GlueVerdict> for GlueOutput { + fn from(g: &GlueVerdict) -> Self { + Self { + check: g.check.clone(), + tokens: g.tokens, + failing_tokens: g.failing_tokens, + max_error: g.max_error, + worst: g.worst.clone(), + failures: g.failures.clone(), + pass: g.pass, + } + } +} + +/// What checking one layer cost this machine, measured. +#[derive(Clone, Default, Serialize)] +pub struct CostOutput { + pub positions: usize, + /// Loading the layer alone on the CPU. + pub layer_load_seconds: f64, + /// Each evaluation of the layer at every opened position; the first + /// includes creating the evaluation context. + pub glue_eval_seconds: Vec, + /// The whole glue check: evaluation and comparisons. + pub glue_check_seconds: f64, + /// Reading weight rows and checking the matmul columns. + pub row_check_seconds: f64, +} + +impl CostOutput { + /// The fastest evaluation, per opened position. + pub(crate) fn eval_ms_per_position(&self) -> f64 { + let best = self + .glue_eval_seconds + .iter() + .copied() + .fold(f64::INFINITY, f64::min); + best * 1000.0 / self.positions.max(1) as f64 + } +} + +#[derive(Serialize)] +pub struct MatrixOutput { + pub weight: String, + pub weight_type: String, + pub router: bool, + pub tokens: usize, + pub failing_tokens: usize, + pub repaired_tokens: usize, + pub max_error: f64, + pub best_profile: String, +} + +impl From<&MatrixVerdict> for MatrixOutput { + fn from(m: &MatrixVerdict) -> Self { + Self { + weight: m.weight.clone(), + weight_type: m.weight_type.clone(), + router: m.router, + tokens: m.tokens, + failing_tokens: m.failing_tokens, + repaired_tokens: m.repaired_tokens, + max_error: m.max_error, + best_profile: m.best_profile.to_string(), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipt-audit/src/output/tests.rs b/crates/skippy-receipt-audit/src/output/tests.rs new file mode 100644 index 00000000..bf42f164 --- /dev/null +++ b/crates/skippy-receipt-audit/src/output/tests.rs @@ -0,0 +1,395 @@ +use skippy_receipts::toy_turn::Turn; +use skippy_receipts::turn::TurnBinding; + +use super::*; +use crate::attention_audit::AttentionOutput; + +/// The output of an audit whose every check ran and held. +fn passing() -> AuditOutput { + let turn = Turn::new(); + let challenge = turn.challenge(&[(0, &[1, 3])], &[]); + let mut output = AuditOutput::new("Paris.".into(), turn.receipt, challenge); + output.layers.push(layer(0)); + output.anchors = Check::Verdict(glue_verdict(true)); + output.attention = Some(AttentionOutput::default()); + output +} + +fn layer(layer: u32) -> LayerOutput { + LayerOutput { + layer, + matrices: Vec::new(), + rows_fault: None, + rows_error: None, + glue: vec![glue_verdict(true)], + glue_pass: true, + glue_fault: None, + glue_error: None, + unchecked_weights: Vec::new(), + cost: CostOutput::default(), + } +} + +fn glue_verdict(pass: bool) -> GlueOutput { + GlueOutput { + check: "anchors".into(), + tokens: 2, + failing_tokens: usize::from(!pass) * 2, + max_error: 0.0, + worst: String::new(), + failures: Vec::new(), + pass, + } +} + +fn finished(change: impl FnOnce(&mut AuditOutput)) -> AuditOutput { + let mut output = passing(); + change(&mut output); + output.finish(); + output +} + +#[test] +fn every_check_held_is_a_pass() { + let output = finished(|_| {}); + assert_eq!(output.outcome, Outcome::Pass); + assert!(output.pass && output.failures.is_empty() && output.unchecked.is_empty()); +} + +#[test] +fn a_check_that_could_not_run_is_no_audit_and_not_a_failure() { + // a weight read that failed, a layer that did not load: the report + // used to end `AUDIT FAIL` for these, against an honest node + type Change = fn(&mut AuditOutput); + let unavailable: [Change; 5] = [ + |o| o.anchors = Check::Unavailable("the layer did not load".into()), + |o| { + o.layers[0].glue_error = Some("the layer did not load".into()); + o.layers[0].glue_pass = false; + }, + |o| o.layers[0].rows_error = Some("connection reset".into()), + |o| o.head = Some(Check::Unavailable("connection reset".into())), + |o| o.tokens = Some(Check::Unavailable("the vocabulary did not load".into())), + ]; + for (i, change) in unavailable.into_iter().enumerate() { + let output = finished(change); + assert_eq!(output.outcome, Outcome::NoAudit, "check {i}"); + assert!(!output.pass && output.failures.is_empty(), "check {i}"); + assert_eq!(output.unchecked.len(), 1, "check {i}"); + assert!( + output.render_text().ends_with("NO AUDIT\n"), + "check {i}: {}", + output.render_text() + ); + } +} + +#[test] +fn a_defect_of_the_nodes_answer_is_a_failure_the_evidence_shows() { + type Change = fn(&mut AuditOutput); + let faults: [Change; 8] = [ + // a receipt the node signed that is no turn of the claimed model: + // the receipt itself shows it + |o| o.receipt_error = Some("stage 1 commits a cached prefix of no positions".into()), + |o| o.opening_error = Some("the opening holds stages [99, 0, 1]".into()), + |o| o.anchors = Check::NodeFault("an anchor is not a number".into()), + |o| o.anchors = Check::Verdict(glue_verdict(false)), + |o| o.layers[0].glue_fault = Some("opened matmul output 0 changes length".into()), + |o| o.layers[0].rows_fault = Some("matmul 0 is opened more than once".into()), + |o| o.layers[0].glue_pass = false, + // a node that left its logits out: a recheck reads the opening too, + // and judges the token on no other logits + |o| o.head = Some(Check::NodeFault("position 4 opened no logits".into())), + ]; + for (i, change) in faults.into_iter().enumerate() { + let output = finished(change); + assert_eq!(output.outcome, Outcome::Fail, "fault {i}"); + assert_eq!(output.failures.len(), 1, "fault {i}: {:?}", output.failures); + assert!(output.failures[0].provable, "fault {i}"); + assert!(output.provable()); + assert!(output.render_text().ends_with("AUDIT FAIL\n")); + } +} + +#[test] +fn what_only_the_client_saw_is_a_failure_no_evidence_shows() { + let tokens = |response_ok, prompt_ok| TokenOutput { + generated: "Paris.".into(), + response_ok, + prompt_ok, + prompt_compared: String::new(), + }; + type Change = Box; + let unprovable: Vec = vec![ + Box::new(move |o| o.tokens = Some(Check::Verdict(tokens(false, true)))), + Box::new(move |o| o.tokens = Some(Check::Verdict(tokens(true, false)))), + Box::new(|o| { + o.request_errors + .push("the node says a grammar constrained the tokens".into()) + }), + Box::new(|o| o.binding_error = Some("the receipt names another client key".into())), + ]; + for (i, change) in unprovable.into_iter().enumerate() { + let output = finished(change); + assert_eq!(output.outcome, Outcome::Fail, "failure {i}"); + assert_eq!(output.failures.len(), 1, "failure {i}"); + assert!(!output.failures[0].provable, "failure {i}"); + assert!(!output.provable()); + assert!(output.render_text().contains("(seen by this client alone)")); + } +} + +/// A head whose token fails, and whose logits a key check judged as +/// `logits_ok` says. +fn head(logits_ok: Option) -> HeadOutput { + head_with(logits_ok, false) +} + +/// [`head`], with whether the token passed on the node's own logits. +fn head_with(logits_ok: Option, token_ok: bool) -> HeadOutput { + HeadOutput { + positions: vec![HeadPositionOutput { + position: 4, + sampled: 3, + best: 5, + margin: -1.0, + band: 0.01, + within_band: false, + judged: true, + key_margin: logits_ok.map(|ok| if ok { 2 } else { -1 }), + every_row_error: None, + row_error: logits_ok.map(|_| 0.0), + logits_ok, + rounding_flips: None, + draw: None, + forced: None, + token_ok, + pass: false, + }], + ties: 0, + band_draws: 0, + flagged: false, + pass: false, + seconds: 0.0, + keyed: logits_ok.is_some(), + every_row: false, + key_build_seconds: None, + rule: "the greedy choice".into(), + reasoning: None, + } +} + +#[test] +fn a_head_failure_is_shown_by_the_evidence_when_the_token_is_wrong() { + // the node's logits give another token: a recheck judges the same + // logits + for logits_ok in [None, Some(true)] { + let output = finished(|o| o.head = Some(Check::Verdict(head(logits_ok)))); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.failures[0].provable, "{logits_ok:?}"); + } + // and so is a token the node's own logits refuse, whatever the key + // found of those logits + let output = finished(|o| o.head = Some(Check::Verdict(head(Some(false))))); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.failures[0].provable); + let text = output.render_text(); + assert!( + text.contains("token refused on the node's own logits"), + "{text}" + ); + // logits only the client's key refused are not: nobody else has the key + let output = finished(|o| o.head = Some(Check::Verdict(head_with(Some(false), true)))); + assert_eq!(output.outcome, Outcome::Fail); + assert!(!output.failures[0].provable); + // the report shows how far off they were, never the key's error + let text = output.render_text(); + assert!( + text.contains("refused by the head key, over its tolerance by less than 10 times"), + "{text}" + ); + // logits a check of every row refused are: anyone reads the rows + let output = finished(|o| { + let mut head = head(Some(false)); + head.keyed = false; + head.every_row = true; + let position = &mut head.positions[0]; + position.key_margin = None; + position.every_row_error = Some(0.5); + o.head = Some(Check::Verdict(head)); + }); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.failures[0].provable); + assert!(output.render_text().contains("error over every row")); +} + +#[test] +fn rows_the_node_did_not_open_leave_the_audit_unanswered() { + let unanswered = |o: &mut AuditOutput| { + o.attention = Some(AttentionOutput { + rows_unanswered: Some("the peer did not answer in time".into()), + ..AttentionOutput::default() + }); + }; + let output = finished(unanswered); + assert_eq!(output.outcome, Outcome::Unanswered); + assert!(!output.pass && output.failures.is_empty() && output.unchecked.is_empty()); + assert!(output.render_text().ends_with("NO ANSWER\n")); + // a failure found before stands + let output = finished(|o| { + unanswered(o); + o.anchors = Check::Verdict(glue_verdict(false)); + }); + assert_eq!(output.outcome, Outcome::Fail); + // and a check that could not run does not turn it into no audit + let output = finished(|o| { + unanswered(o); + o.anchors = Check::Unavailable("the layer did not load".into()); + }); + assert_eq!(output.outcome, Outcome::Unanswered); +} + +#[test] +fn evidence_without_its_rows_is_incomplete_and_not_a_failure() { + // a recheck of evidence whose rows were removed used to report the + // attention rows as failed + let output = finished(|o| { + o.attention = Some(AttentionOutput { + rows_missing: Some("the evidence holds no attention rows".into()), + ..AttentionOutput::default() + }); + }); + assert_eq!(output.outcome, Outcome::NoAudit); + assert!(output.failures.is_empty()); + assert_eq!( + output.unchecked, + ["attention rows: the evidence holds no attention rows"] + ); + // rows the node signed that are defective are a failure + let output = finished(|o| { + o.attention = Some(AttentionOutput { + rows_error: Some("the row at position 3 of layer 1 is not opened".into()), + ..AttentionOutput::default() + }); + }); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.failures[0].provable); +} + +#[test] +fn a_refused_receipt_or_opening_lists_no_check_as_unavailable() { + // the checks did not run; they are not "could not run here" + let output = finished(|o| { + o.opening_error = Some("layer 3 was not opened".into()); + o.layers.clear(); + }); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.unchecked.is_empty()); +} + +#[test] +fn every_output_carries_its_outcome_and_pass() { + let json = |value: serde_json::Value| (value["outcome"].clone(), value["pass"].clone()); + let audited = |output: &AuditOutput| json(serde_json::to_value(output).unwrap()); + assert_eq!(audited(&finished(|_| {})), ("pass".into(), true.into())); + let failed = finished(|o| o.anchors = Check::Verdict(glue_verdict(false))); + assert_eq!(audited(&failed), ("fail".into(), false.into())); + let unchecked = finished(|o| o.anchors = Check::Unavailable("offline".into())); + assert_eq!(audited(&unchecked), ("no_audit".into(), false.into())); + let no_audit = NoAuditOutput::new("r1", "no rounding profiles for backend MTL0 yet"); + assert_eq!( + json(serde_json::to_value(&no_audit).unwrap()), + ("no_audit".into(), false.into()) + ); + let unanswered = UnansweredOutput::new("r1", "open", "connection refused"); + let value = serde_json::to_value(&unanswered).unwrap(); + assert_eq!(value["request"], "open"); + assert_eq!(json(value), ("unanswered".into(), false.into())); + // a failure says whether the evidence shows it + let value = serde_json::to_value(&failed).unwrap(); + assert_eq!(value["failures"][0]["provable"], true); + assert_eq!(value["failures"][0]["check"], "input of layer 0"); +} + +#[test] +fn a_turn_that_continued_a_cached_prefix_reports_its_prompt_over_the_prefix() { + let turn = Turn::starting_at(40); + let challenge = turn.challenge(&[(0, &[7, 41])], &[]); + let finished = |prompt_ok: bool| { + let (receipt, challenge) = (turn.receipt.clone(), challenge.clone()); + let mut output = AuditOutput::new("Paris.".into(), receipt, challenge); + output.layers.push(layer(0)); + output.anchors = Check::Verdict(glue_verdict(true)); + output.attention = Some(AttentionOutput::default()); + output.tokens = Some(Check::Verdict(TokenOutput { + generated: "Paris.".into(), + response_ok: true, + prompt_ok, + prompt_compared: crate::token_check::PromptMatch::Turn.describe().to_owned(), + })); + output.finish(); + output + }; + // the prefix is checked like the turn: nothing is left to note + let output = finished(true); + assert_eq!(output.outcome, Outcome::Pass); + assert!(output.notes.is_empty(), "{:?}", output.notes); + let value = serde_json::to_value(&output).unwrap(); + assert_eq!(value["tokens"]["verdict"]["prompt_ok"], true); + let text = output.render_text(); + assert!( + text.contains( + "prompt message is where the turn read it: ok (the message ends in the turn's own tokens, after a cached prefix of 40 positions; the system prompt and history are not compared)" + ), + "{text}" + ); + // a prompt that is not in the prefix and the turn is a failure + assert_eq!(finished(false).outcome, Outcome::Fail); +} + +#[test] +fn a_nodes_text_cannot_forge_a_line_of_the_report() { + let forged = "x\nAUDIT PASS\n\x1b[1A"; + let mut output = passing(); + output.response = format!("Paris.{forged}"); + output.receipt.receipt_id = format!("r1{forged}"); + output.receipt.model = format!("model{forged}"); + for stage in &mut output.receipt.stages { + stage.backend = format!("CPU{forged}"); + stage.cache_types = vec![format!("f16{forged}")]; + // a root that is not hex, cut inside a character by a byte slice + stage.root = "aéééééééé\nAUDIT PASS".into(); + } + output.receipt.binding = Some(TurnBinding { + client_key: forged.into(), + parent: None, + runtime: format!("skippy-abi 1.2.3{forged}"), + sampler: format!("greedy{forged}"), + node_key: "ключ\r\nAUDIT PASS".into(), + turn_root: forged.into(), + signature: String::new(), + }); + output.tokens = Some(Check::Verdict(TokenOutput { + generated: forged.into(), + response_ok: false, + prompt_ok: true, + prompt_compared: String::new(), + })); + output.layers[0].glue_fault = Some(format!("blk.0{forged}.weight changes length")); + output.layers[0].unchecked_weights = vec![forged.into()]; + output.anchors = Check::NodeFault(forged.into()); + output.finish(); + assert_eq!(output.outcome, Outcome::Fail); + let text = output.render_text(); + let lines: Vec<&str> = text.lines().collect(); + // the node wrote `AUDIT PASS` into every text it chose; the one line + // that names the outcome is the report's own, and it is the last + let verdicts: Vec<&&str> = lines + .iter() + .filter(|line| line.trim().starts_with("AUDIT") || line.trim().starts_with("NO A")) + .collect(); + assert_eq!(verdicts, [&"AUDIT FAIL"], "{text}"); + assert_eq!(lines.last(), Some(&"AUDIT FAIL")); + assert!(!text.contains('\x1b') && !text.contains('\r'), "{text:?}"); + assert!(text.contains("\\nAUDIT PASS"), "{text}"); +} diff --git a/crates/skippy-receipt-audit/src/recheck.rs b/crates/skippy-receipt-audit/src/recheck.rs new file mode 100644 index 00000000..61479c9e --- /dev/null +++ b/crates/skippy-receipt-audit/src/recheck.rs @@ -0,0 +1,172 @@ +//! Checks an audit's evidence again from the evidence and the claimed GGUF +//! alone, as `skippy recheck-receipt` does. +//! +//! First it shows that the evidence is what it says: the node signed the +//! receipt, the opening and the attention rows, and the client's VRF drew +//! the challenge and the checked rows. Then it runs the audit's checks on +//! the opening again, on the same path an audit takes: the opening's form +//! and Merkle paths, every value against the claimed model, and then the +//! checks. Anyone with the claimed GGUF gets the same verdict, so a +//! failure the client shows is the node's. The output head is checked +//! without the client's secret key, on every row of the output matrix, +//! which accepts the logits the key accepts. +//! +//! A file that is not evidence, a model this machine cannot check, and +//! evidence without the attention rows are no audit: none of them says +//! anything about the node. + +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::binding; +use skippy_receipts::coverage; +use skippy_receipts::evidence::{Evidence, Provenance}; +use skippy_receipts::node_fault::NodeFault; +use skippy_receipts::opened_values; +use skippy_receipts::weights::WeightFile; + +use crate::attention_audit::{self, OpenedRows, RowsAnswer}; +use crate::claimed_model::ClaimedModel; +use crate::opening_checks::{Checks, check_opening}; +use crate::output::{AuditOutput, NoAuditOutput}; +use crate::turn_audit::{TurnAudit, executable_layer_bytes, fits_claimed_model}; + +/// Runs the audit's checks on `evidence` again. +pub fn recheck_evidence( + evidence: &Evidence, + weights: &WeightFile, + model: &dyn ClaimedModel, + layer_count: u32, +) -> TurnAudit { + let id = evidence.receipt.receipt_id.as_str(); + let no_audit = |reason: String| TurnAudit::NoAudit(NoAuditOutput::new(id, reason)); + let provenance = match evidence.verify(&executable_layer_bytes(weights, layer_count)) { + Ok(provenance) => provenance, + // nothing in such a file is known to be the node's + Err(error) => return no_audit(format!("not evidence of an audit: {error:#}")), + }; + if let Some(reason) = coverage::unauditable(&evidence.receipt, weights, &model.runtime()) { + return no_audit(format!("cannot recheck this evidence here: {reason}")); + } + let mut output = AuditOutput::new( + String::new(), + evidence.receipt.clone(), + evidence.challenge.clone(), + ); + output.rows_proof = Some(evidence.rows_proof.clone()); + // the same path an audit takes: the receipt against the claimed model, + // the opening's form and paths, then every value against the model + if let Err(error) = fits_claimed_model(weights, layer_count, &evidence.receipt) { + return refused(output, &error, |output, reason| { + output.receipt_error = Some(reason); + }); + } + let validated = + binding::verify_paths(&evidence.receipt, &evidence.challenge, &provenance.opening) + .and_then(|verified| opened_values::validate(verified, weights)); + let validated = match validated { + Ok(validated) => validated, + Err(error) => { + return refused(output, &error, |output, reason| { + output.opening_error = Some(reason); + }); + } + }; + let checks = Checks { + timing_runs: 1, + response: None, + // the key is secret: a recheck checks the logits on every row + head_key: None, + }; + let layouts = check_opening( + &checks, + model, + weights, + &validated, + &provenance.rows_seed, + &mut output, + ); + // the rows the node sent answer the blocks the same seed draws again + let open_rows = |blocks: &BlockChallenge| evidence_rows(&provenance, blocks); + let (attention, _) = + attention_audit::check_attention(&validated, &layouts, &provenance.rows_seed, &open_rows); + output.attention = Some(attention); + note_no_request(&mut output); + output.finish(); + TurnAudit::Audited { + output: Box::new(output), + evidence: None, + } +} + +/// A recheck has no request to hold the sampler statement to. What the +/// statement leaves unjudged stays so, and the report says that an audit +/// with the request would have asked whether the client asked for it. +fn note_no_request(output: &mut AuditOutput) { + let Some(binding) = output.receipt.binding.as_ref() else { + return; + }; + let Some(stated) = skippy_receipts::turn::sampler_parameters(&binding.sampler) else { + return; + }; + let mut gaps: Vec = skippy_receipts::head::sampling::gaps(&stated) + .unwrap_or_default() + .iter() + .map(skippy_receipts::head::sampling::Gap::describe) + .collect(); + if !stated[skippy_receipts::turn::REASONING].is_null() { + gaps.push("a reasoning budget forced tokens".into()); + } + if !gaps.is_empty() { + output.notes.push(format!( + "not checked: whether the client asked for what the node states ({}); a recheck has no request, so it reads the statement as the node wrote it", + gaps.join(", ") + )); + } +} + +/// A receipt or an opening the checks refuse: a failure when the error +/// blames the node, else no audit. +fn refused( + mut output: AuditOutput, + error: &anyhow::Error, + record: impl FnOnce(&mut AuditOutput, String), +) -> TurnAudit { + if NodeFault::find(error).is_none() { + let id = output.receipt.receipt_id; + return TurnAudit::NoAudit(NoAuditOutput::new(id, format!("{error:#}"))); + } + record(&mut output, format!("{error:#}")); + output.finish(); + TurnAudit::Audited { + output: Box::new(output), + evidence: None, + } +} + +/// The attention rows of the evidence, for the blocks a recheck draws. +/// Evidence without rows, or with rows the node signed for other blocks, +/// is incomplete: the blocks cannot be checked, which is no failure. Rows +/// the node signed for these blocks that do not decode are its defect. +pub(crate) fn evidence_rows(provenance: &Provenance, blocks: &BlockChallenge) -> RowsAnswer { + let Some(rows) = provenance.rows.as_ref() else { + return RowsAnswer::Missing("the evidence holds no attention rows".into()); + }; + let bytes = match rows.answering(&provenance.binding, blocks) { + Ok(bytes) => bytes.to_vec(), + Err(error) => { + return RowsAnswer::Missing(format!( + "the evidence holds no attention rows the node signed for these blocks: {error:#}" + )); + } + }; + match serde_json::from_slice(&bytes) { + Ok(decoded) => RowsAnswer::Signed(OpenedRows { + rows: decoded, + bytes, + signature: Some(rows.signature().to_owned()), + seconds: 0.0, + }), + Err(error) => { + RowsAnswer::Defective(format!("the signed attention rows do not decode: {error}")) + } + } +} diff --git a/crates/skippy-receipt-audit/src/recurrent_audit.rs b/crates/skippy-receipt-audit/src/recurrent_audit.rs new file mode 100644 index 00000000..4fbb501b --- /dev/null +++ b/crates/skippy-receipt-audit/src/recurrent_audit.rs @@ -0,0 +1,247 @@ +//! The recurrent check of an audited turn ([`skippy_receipts::recurrent`]): +//! for each stage, the first attention pick on a layer whose token mixing +//! reads a recurrent state, as the auditor's own graph has it, must come +//! with the ubatch that computed it. The auditor recomputes the ubatch's +//! token mixing from the opened inputs and state. + +use std::collections::BTreeSet; +use std::io::Write; + +use serde::Serialize; +use skippy_receipts::attention::opening::AttentionPick; +use skippy_receipts::node_fault::NodeFault; +use skippy_receipts::opened_values::ValidatedOpening; +use skippy_receipts::recurrent::{check_region, region_pick}; +use skippy_receipts::wire::{RecurrentOpening, StageCommitment}; + +use crate::claimed_model::{CacheTypes, ClaimedModel}; +use crate::node_text::shown; +use crate::output::GlueOutput; + +#[derive(Serialize)] +pub struct RecurrentOutput { + pub position: u32, + pub layer: u32, + /// The ubatch's positions, as opened. + pub start: Option, + pub end: Option, + pub verdicts: Vec, + pub eval_seconds: Option, + /// Why the check could not run here; says nothing about the node. + pub unchecked: Option, + /// Why the region failed. + pub failure: Option, + pub pass: bool, +} + +impl RecurrentOutput { + fn new(position: u32, layer: u32) -> Self { + Self { + position, + layer, + start: None, + end: None, + verdicts: Vec::new(), + eval_seconds: None, + unchecked: None, + failure: None, + pass: false, + } + } +} + +/// The layers of an audit whose glue ran, so the auditor knows from its own +/// graph whether each keeps a recurrent state. +pub(crate) struct KnownLayers<'a> { + /// The picked layers whose glue ran. + pub(crate) evaluated: &'a BTreeSet, + /// Those of them that keep a recurrent state. + pub(crate) state: &'a BTreeSet, +} + +/// Checks the region of every stage that holds a picked layer the +/// auditor's graph gives a recurrent state, and that no other stage opened +/// one. +pub(crate) fn check_recurrent( + model: &dyn ClaimedModel, + opening: &ValidatedOpening<'_>, + layers: &KnownLayers<'_>, +) -> Vec { + opening + .receipt() + .stages + .iter() + .filter_map(|stage| check_stage(model, opening, stage, layers)) + .collect() +} + +fn check_stage( + model: &dyn ClaimedModel, + opening: &ValidatedOpening<'_>, + stage: &StageCommitment, + layers: &KnownLayers<'_>, +) -> Option { + let held = stage.layer_start..stage.layer_end; + let pick = region_pick(opening.challenge(), &held, layers.state); + let region = opening.region(stage); + let (Some(pick), Some(region)) = (pick, region) else { + return unpaired(pick, region, layers); + }; + let mut output = RecurrentOutput::new(pick.position, pick.layer); + if (region.position, region.layer) != (pick.position, pick.layer) { + output.failure = Some(format!( + "the stage opened the region of position {}, layer {}, not of its first pick on a \ + layer that keeps a state", + region.position, region.layer + )); + return Some(output); + } + check_one(model, opening, pick, region, &mut output); + Some(output) +} + +/// A stage that owes a region and opened none, or opened one it does not +/// owe. The second is a failure only where the auditor's own graph says +/// the layer keeps no state. +fn unpaired( + pick: Option<&AttentionPick>, + region: Option<&RecurrentOpening>, + layers: &KnownLayers<'_>, +) -> Option { + match (pick, region) { + (Some(pick), _) => { + let mut output = RecurrentOutput::new(pick.position, pick.layer); + output.failure = Some("the stage opened no recurrent region".into()); + Some(output) + } + (None, Some(region)) => { + let mut output = RecurrentOutput::new(region.position, region.layer); + output.start = Some(region.start); + output.end = Some(region.end); + if layers.evaluated.contains(®ion.layer) { + output.failure = Some( + "the stage opened a recurrent region on a layer that keeps no state".into(), + ); + } else { + output.unchecked = Some("the layer's glue did not run".into()); + } + Some(output) + } + (None, None) => None, + } +} + +fn check_one( + model: &dyn ClaimedModel, + opening: &ValidatedOpening<'_>, + pick: &AttentionPick, + region: &RecurrentOpening, + output: &mut RecurrentOutput, +) { + output.start = Some(region.start); + output.end = Some(region.end); + // the width of the residual stream, from the picked layer's opening + let residual_len = opening + .leaf(pick.layer, pick.position) + .and_then(|leaf| leaf.residual_in_values().ok()) + .map(|residual| residual.len()); + let Some(residual_len) = residual_len else { + output.unchecked = Some("the attention position is not a picked one".into()); + return; + }; + let mut report = None; + let checked = model.with_layer(pick.layer, CacheTypes::default(), &mut |evaluator| { + report = Some(check_region(evaluator, region, residual_len)?); + Ok(()) + }); + match (checked, report) { + (Ok(()), Some(report)) => { + output.verdicts = report.verdicts.iter().map(GlueOutput::from).collect(); + output.eval_seconds = Some(report.eval_seconds); + output.pass = report.pass; + if !report.pass { + output.failure = Some("the recomputed region differs".into()); + } + } + // a region that makes no request is the node's; a layer that does + // not load or compute is the client's + (Err(error), _) if NodeFault::find(&error).is_some() => { + output.failure = Some(format!("{error:#}")); + } + (Err(error), _) => output.unchecked = Some(format!("{error:#}")), + (Ok(()), None) => output.unchecked = Some("the region was not checked".into()), + } +} + +pub(crate) fn failures(recurrent: &[RecurrentOutput]) -> Vec { + recurrent + .iter() + .filter_map(|r| { + Some(format!( + "recurrent region at position {}, layer {}: {}", + r.position, + r.layer, + r.failure.as_ref()? + )) + }) + .collect() +} + +pub(crate) fn unchecked(recurrent: &[RecurrentOutput]) -> Vec { + recurrent + .iter() + .filter_map(|r| { + Some(format!( + "recurrent region of layer {}: {}", + r.layer, + r.unchecked.as_ref()? + )) + }) + .collect() +} + +pub(crate) fn render(out: &mut dyn Write, recurrent: &[RecurrentOutput]) -> std::io::Result<()> { + if recurrent.is_empty() { + return Ok(()); + } + writeln!(out, "recurrent token mixing, per stage:")?; + for r in recurrent { + let span = match (r.start, r.end) { + (Some(start), Some(end)) => format!("positions {start}..{end}"), + _ => "-".into(), + }; + let what = format!("position {} layer {}", r.position, r.layer); + if let Some(reason) = &r.unchecked { + writeln!(out, " {what:<26} cannot check ({})", shown(reason))?; + continue; + } + writeln!( + out, + " {what:<26} {span} {}{}{}", + if r.pass { "ok" } else { "FAIL" }, + r.eval_seconds + .map(|s| format!(" ({s:.2} s)")) + .unwrap_or_default(), + r.failure + .as_ref() + .map(|f| format!(" ({})", shown(f))) + .unwrap_or_default() + )?; + for v in &r.verdicts { + writeln!( + out, + " {:<18} {:>4}/{:<4} pass max err {:.1e}{}", + shown(&v.check), + v.tokens - v.failing_tokens, + v.tokens, + v.max_error, + if v.pass { + String::new() + } else { + format!(" worst: {}", shown(&v.worst)) + } + )?; + } + } + Ok(()) +} diff --git a/crates/skippy-receipt-audit/src/report_text.rs b/crates/skippy-receipt-audit/src/report_text.rs new file mode 100644 index 00000000..5ac6ec0f --- /dev/null +++ b/crates/skippy-receipt-audit/src/report_text.rs @@ -0,0 +1,486 @@ +//! The text report of an audit, as `skippy audit-receipt` and +//! `skippy recheck-receipt` print it. Its last line is the outcome: +//! `AUDIT PASS`, `AUDIT FAIL`, `NO AUDIT` or `NO ANSWER`. +//! +//! Much of what a report shows is text the node chose. Every such text +//! goes through [`shown`], so a report has the lines this module writes +//! and no others. + +use std::io::Write; + +use skippy_receipts::wire::Receipt; + +use crate::node_text::{short, shown}; +use crate::outcome::{Check, Outcome}; +use crate::output::{ + AuditOutput, HeadOutput, LayerOutput, NoAuditOutput, TokenOutput, UnansweredOutput, +}; +use crate::recurrent_audit; + +fn ok(pass: bool) -> &'static str { + if pass { "ok" } else { "FAIL" } +} + +/// A key check's margin in words. +fn key_margin_text(margin: i8) -> String { + let factor = |decades: i8| 10u32.pow(u32::from(decades.unsigned_abs())); + match margin { + 0 => "under its tolerance by less than 10 times".to_owned(), + -1 => "over its tolerance by less than 10 times".to_owned(), + m if m > 0 => format!("under its tolerance by {} times or more", factor(m)), + m => format!("over its tolerance by {} times or more", factor(m + 1)), + } +} + +pub fn render_no_audit(out: &mut dyn Write, output: &NoAuditOutput) -> std::io::Result<()> { + writeln!( + out, + "receipt {}: {}", + shown(&output.receipt_id), + shown(&output.reason) + )?; + writeln!(out, "{}", Outcome::NoAudit.line()) +} + +pub fn render_unanswered(out: &mut dyn Write, output: &UnansweredOutput) -> std::io::Result<()> { + writeln!( + out, + "receipt {}: the node did not answer /receipts/{}: {}", + shown(&output.receipt_id), + output.request, + shown(&output.reason) + )?; + writeln!(out, "{}", Outcome::Unanswered.line()) +} + +pub fn render(out: &mut dyn Write, output: &AuditOutput) -> std::io::Result<()> { + if output.tokens.is_some() { + writeln!(out, "response: {}", shown(output.response.trim()))?; + writeln!(out)?; + } + render_receipt(out, &output.receipt)?; + for pick in &output.challenge.picks { + let stage = output + .receipt + .stage_for_layer(pick.layer) + .map_or(0, |s| s.stage_index); + writeln!( + out, + "challenge: layer {} (stage {stage}), positions {:?}", + pick.layer, pick.positions + )?; + } + if let Some(seconds) = output.open_seconds { + writeln!(out, "opening: {seconds:.2} s")?; + } + if output.hand_picked { + writeln!( + out, + "challenge picked by hand (--layer), not drawn from the VRF: not evidence" + )?; + } + render_binding(out, output)?; + for layer in &output.layers { + render_layer(out, layer)?; + } + if !output.roles.is_empty() { + writeln!(out, "weight rows, each role across the opened layers:")?; + } + for r in &output.roles { + writeln!( + out, + " {:<24} {:>3}/{:<3} pass {}{}", + shown(&r.role), + r.tokens - r.failing_tokens, + r.tokens, + ok(r.pass), + if r.router { + " (router, no failure allowed)" + } else { + "" + } + )?; + } + if output.opened() { + render_checks(out, output)?; + } + for note in &output.notes { + writeln!(out, "note: {}", shown(note))?; + } + for failure in &output.failures { + writeln!( + out, + "failed: {}{}", + shown(&failure.check), + if failure.provable { + "" + } else { + " (seen by this client alone)" + } + )?; + } + for unchecked in &output.unchecked { + writeln!(out, "could not check: {}", shown(unchecked))?; + } + writeln!(out, "{}", output.outcome.line()) +} + +fn render_binding(out: &mut dyn Write, output: &AuditOutput) -> std::io::Result<()> { + for error in &output.request_errors { + writeln!(out, "receipt against the request: FAIL ({})", shown(error))?; + } + if let Some(error) = &output.binding_error { + return writeln!( + out, + "receipt binding and signature: FAIL ({})", + shown(error) + ); + } + if let Some(error) = &output.receipt_error { + return writeln!( + out, + "receipt shape against the claimed model: FAIL ({})", + shown(error) + ); + } + match &output.opening_error { + Some(error) => writeln!( + out, + "opening form, merkle paths and values: FAIL ({})", + shown(error) + ), + None => writeln!( + out, + "receipt binding and signature, shape, opening form, merkle paths, stage boundaries \ + and values: ok" + ), + } +} + +/// The checks of the opened values, which ran because the receipt and the +/// opening were accepted. +fn render_checks(out: &mut dyn Write, output: &AuditOutput) -> std::io::Result<()> { + match &output.anchors { + Check::Verdict(a) => writeln!( + out, + "input of layer 0 from the receipt's tokens: {}/{} pass max err {:.1e} {}", + a.tokens - a.failing_tokens, + a.tokens, + a.max_error, + ok(a.pass) + )?, + Check::NodeFault(fault) => writeln!(out, "input of layer 0: FAIL ({})", shown(fault))?, + Check::Unavailable(reason) => { + writeln!(out, "input of layer 0: cannot check ({})", shown(reason))?; + } + } + render_head(out, output.head.as_ref())?; + if let Some(attention) = &output.attention { + crate::attention_audit::render(out, attention)?; + } + recurrent_audit::render(out, &output.recurrent)?; + match &output.tokens { + Some(tokens) => render_tokens(out, tokens, &output.receipt), + None => writeln!( + out, + "response: not part of the evidence (the node does not sign it)" + ), + } +} + +fn render_receipt(out: &mut dyn Write, receipt: &Receipt) -> std::io::Result<()> { + writeln!( + out, + "receipt {} model {} positions {}..{} generation from {}", + shown(&receipt.receipt_id), + shown(&receipt.model), + receipt.position_start, + receipt.position_end, + receipt.generation_start + )?; + for stage in &receipt.stages { + writeln!( + out, + " stage {} layers {:>2}..{:<2} root {}… leaves {} cache {} ({})", + stage.stage_index, + stage.layer_start, + stage.layer_end, + short(&stage.root, 16), + stage.leaf_count, + shown(&stage.cache_types.join(",")), + shown(&stage.backend) + )?; + } + if let Some(binding) = &receipt.binding { + writeln!( + out, + " turn root {}… node key {}… client key {}… {} sampler {}", + short(&binding.turn_root, 16), + short(&binding.node_key, 16), + short(&binding.client_key, 16), + shown(&binding.runtime), + shown(&binding.sampler) + )?; + } + Ok(()) +} + +fn render_layer(out: &mut dyn Write, layer: &LayerOutput) -> std::io::Result<()> { + writeln!(out, "layer {}:", layer.layer)?; + for m in &layer.matrices { + writeln!( + out, + " {:<30} {:<5} {:>3}/{:<3} pass max err {:.1e} {}{}{}", + shown(&m.weight), + shown(&m.weight_type), + m.tokens - m.failing_tokens, + m.tokens, + m.max_error, + m.best_profile, + match m.repaired_tokens { + 0 => String::new(), + n => format!(" ({n} repaired near-ties)"), + }, + if m.router { " (router, all rows)" } else { "" } + )?; + } + if let Some(fault) = &layer.rows_fault { + writeln!(out, " weight rows: FAIL ({})", shown(fault))?; + } + if let Some(error) = &layer.rows_error { + writeln!(out, " weight rows: cannot check ({})", shown(error))?; + } + if let Some(fault) = &layer.glue_fault { + writeln!(out, " glue: FAIL ({})", shown(fault))?; + } + if let Some(error) = &layer.glue_error { + writeln!(out, " glue: cannot check ({})", shown(error))?; + } + for g in &layer.glue { + writeln!( + out, + " glue {:<14} {:>3}/{:<3} pass max err {:.1e} {}{}", + shown(&g.check), + g.tokens - g.failing_tokens, + g.tokens, + g.max_error, + ok(g.pass), + if g.pass { + String::new() + } else { + format!(" worst: {}", shown(&g.worst)) + } + )?; + for failure in &g.failures { + writeln!(out, " {}", shown(failure))?; + } + } + if !layer.unchecked_weights.is_empty() { + writeln!( + out, + " unchecked weights (inside token mixing): {}", + shown(&layer.unchecked_weights.join(", ")) + )?; + } + let cost = &layer.cost; + writeln!( + out, + " client cost: layer load {:.2} s, glue {:.2} ms per position ({} positions, first run {:.0} ms), row checks {:.0} ms", + cost.layer_load_seconds, + cost.eval_ms_per_position(), + cost.positions, + cost.glue_eval_seconds.first().copied().unwrap_or(0.0) * 1000.0, + cost.row_check_seconds * 1000.0 + ) +} + +fn render_head(out: &mut dyn Write, head: Option<&Check>) -> std::io::Result<()> { + let h = match head { + None => return Ok(()), + Some(Check::NodeFault(fault)) => { + return writeln!(out, "output head: FAIL ({})", shown(fault)); + } + Some(Check::Unavailable(reason)) => { + return writeln!(out, "output head: cannot check ({})", shown(reason)); + } + Some(Check::Verdict(h)) => h, + }; + let positions: Vec = h.positions.iter().map(|p| p.position).collect(); + writeln!( + out, + "sampled tokens at {positions:?} are {}: {}/{} pass ties {}{} {} ({:.2} s{})", + shown(&h.rule), + h.positions.iter().filter(|p| p.pass).count(), + h.positions.len(), + h.ties, + if h.flagged { " (flagged)" } else { "" }, + ok(h.pass), + h.seconds, + if h.keyed { + ", node's logits checked with the head key" + } else if h.every_row { + ", node's logits checked on every row of the output matrix" + } else { + "" + } + )?; + if let Some(seconds) = h.key_build_seconds { + writeln!(out, " built the head key in {seconds:.2} s")?; + } + for p in h.positions.iter().filter(|p| !p.pass) { + // the key's error says something of the secret key: a report + // shows only how far off it was, in powers of ten + let what = match (p.key_margin, p.every_row_error) { + (Some(margin), _) => format!( + "logits {} the head key, {}", + if p.logits_failed() { + "refused by" + } else { + "accepted by" + }, + key_margin_text(margin) + ), + (None, Some(error)) => format!("error over every row {error:.3e}"), + (None, None) => continue, + }; + writeln!( + out, + " position {}: {what}, row error {:.3e}{}", + p.position, + p.row_error.unwrap_or_default(), + if p.token_ok { + "" + } else { + ", token refused on the node's own logits" + } + )?; + } + for p in h + .positions + .iter() + .filter(|p| p.rounding_flips.unwrap_or(0) > 0) + { + writeln!( + out, + " position {}: {} activation rounding(s) on a boundary, taken the other way", + p.position, + p.rounding_flips.unwrap_or_default() + )?; + } + for p in h + .positions + .iter() + .filter(|p| p.forced.is_none() && (!p.pass || p.within_band)) + { + writeln!( + out, + " position {}: sampled {}, best {}, margin {:.3e} (band {:.3e})", + p.position, p.sampled, p.best, p.margin, p.band + )?; + } + render_reasoning(out, h)?; + render_draws(out, h) +} + +/// The reasoning budget of the turn as the node states it, how many of +/// the checked tokens its sampler forced, and each forced position that +/// holds another token. +fn render_reasoning(out: &mut dyn Write, h: &HeadOutput) -> std::io::Result<()> { + let Some(reasoning) = &h.reasoning else { + return Ok(()); + }; + let ends: Vec = reasoning.ends.iter().map(|end| shown(end)).collect(); + writeln!( + out, + " reasoning budget of {} tokens, from {} to {} as the node states them: forced {} of the checked tokens", + reasoning.budget, + shown(&reasoning.start), + ends.join(" or "), + reasoning.forced + )?; + for p in &h.positions { + let Some(forced) = p.forced.filter(|forced| *forced != p.sampled) else { + continue; + }; + writeln!( + out, + " position {}: the reasoning budget forces token {forced}; the turn sampled {}", + p.position, p.sampled + )?; + } + Ok(()) +} + +/// The replayed draws of a sampled turn: how many pick the sampled token, +/// and each one that does not, or does only within the band. +fn render_draws(out: &mut dyn Write, h: &HeadOutput) -> std::io::Result<()> { + let draws: Vec<_> = h + .positions + .iter() + .filter_map(|p| p.draw.as_ref().map(|draw| (p, draw))) + .collect(); + if draws.is_empty() { + return Ok(()); + } + writeln!( + out, + " draws replayed: {}/{} pick the sampled token, {} only within the band", + draws.iter().filter(|(_, d)| d.pass).count(), + draws.len(), + h.band_draws + )?; + for (p, draw) in draws.iter().filter(|(_, d)| !d.exact) { + writeln!( + out, + " position {}: token {} {}: the draw's uniform is {:.6}, and it picks the token from {:.6} up to {:.6}", + p.position, + p.sampled, + if draw.failed() { + "is not the one the draw picks" + } else { + "is picked only within the band" + }, + draw.uniform, + draw.lower, + draw.upper + )?; + } + Ok(()) +} + +fn render_tokens( + out: &mut dyn Write, + tokens: &Check, + receipt: &Receipt, +) -> std::io::Result<()> { + let t = match tokens { + Check::NodeFault(fault) => return writeln!(out, "tokens: FAIL ({})", shown(fault)), + Check::Unavailable(reason) => { + return writeln!(out, "tokens: cannot check ({})", shown(reason)); + } + Check::Verdict(t) => t, + }; + writeln!( + out, + "response is the text of the sampled tokens: {}", + ok(t.response_ok) + )?; + writeln!( + out, + "prompt message is where the turn read it: {} ({}{}; the system prompt and history are not compared)", + ok(t.prompt_ok), + t.prompt_compared, + if receipt.position_start > 0 { + format!( + ", after a cached prefix of {} positions", + receipt.position_start + ) + } else { + String::new() + } + )?; + if !t.response_ok { + writeln!(out, " sampled text: {}", shown(t.generated.trim()))?; + } + Ok(()) +} diff --git a/crates/skippy-receipt-audit/src/token_check.rs b/crates/skippy-receipt-audit/src/token_check.rs new file mode 100644 index 00000000..727be278 --- /dev/null +++ b/crates/skippy-receipt-audit/src/token_check.rs @@ -0,0 +1,310 @@ +//! The response and the prompt a client holds, against the tokens a +//! receipt names. +//! +//! The response must be exactly the text of the tokens the receipt says +//! were sampled: the reasoning and the content together, up to whitespace +//! and the reasoning markers the output parser removes. A response that +//! drops or adds text fails, and so does an empty one for tokens that make +//! text. +//! +//! A response the node says it cut at the token limit may end before the +//! tokens' text does: the node holds back a character whose last token it +//! did not sample, and a reasoning marker it had only begun. Such a +//! response must be the start of the tokens' text, and what it leaves out +//! must be such an end ([`held_back`]). The node itself says that it cut +//! the response, so the rule lets it leave out nothing else. +//! +//! The prompt must be part of the text of the tokens before them, because +//! the chat template adds its own text around it. Only the message a +//! client passes is compared, usually its last user message: the system +//! prompt, the history and any text the template adds are not. A turn that +//! continued a cached prefix receipts the end of the prompt alone. The rest +//! is in the prefix, whose tokens the node opens with its answer, bound to +//! the digest the receipt commits ([`skippy_receipts::binding`]). +//! +//! A short message could be found anywhere in a long prefix, in an earlier +//! turn. So the message must end in the turn's own tokens ([`PromptMatch`]). +//! A turn whose prompt the prefix held all but its last token of, as when a +//! client sends a request again, is the exception: there the message must +//! be the last one in the prefix, with no more than the chat template's +//! closing text after it ([`TEMPLATE_TAIL_CHARS`]). +//! +//! Neither comparison is part of the evidence: the node signs neither the +//! response nor the request. + +use anyhow::Result; +use skippy_receipts::wire::Receipt; + +use crate::chat_reply::ChatReply; +use crate::claimed_model::ClaimedModel; +use crate::output::TokenOutput; + +/// The most characters the sampled tokens' text may hold past the end of a +/// response cut at the token limit. +const CUT_TAIL_CHARS: usize = 16; + +/// The most characters, whitespace and reasoning markers left out, that a +/// chat template writes after the last message: the end of the message, +/// the start of the reply and an empty reasoning block. +const TEMPLATE_TAIL_CHARS: usize = 128; + +/// Where the client's message was found among the tokens before the +/// sampled ones. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PromptMatch { + /// It ends in the turn's own tokens. + Turn, + /// It is the end of the cached prefix, followed only by the template's + /// closing text. + PrefixEnd, + /// Neither. + Missing, +} + +impl PromptMatch { + /// What was compared, in words, for a report. + pub(crate) fn describe(self) -> &'static str { + match self { + Self::Turn => "the message ends in the turn's own tokens", + Self::PrefixEnd => { + "the message ends the cached prefix; the turn's own tokens hold only the template's text" + } + Self::Missing => { + "the message does not end in the turn's own tokens or the cached prefix" + } + } + } +} + +/// Where `message` ends in the text of `prefix` and then `turn`, the prompt +/// tokens of the cached prefix and of the turn. +fn find_prompt(prefix: &str, turn: &str, message: &str) -> PromptMatch { + let (prefix, turn, message) = (comparable(prefix), comparable(turn), comparable(message)); + let all = format!("{prefix}{turn}"); + let Some(start) = all.rfind(&message) else { + return PromptMatch::Missing; + }; + let end = start + message.len(); + if end > prefix.len() { + PromptMatch::Turn + } else if all.len() - end <= TEMPLATE_TAIL_CHARS { + PromptMatch::PrefixEnd + } else { + PromptMatch::Missing + } +} + +/// Compares `reply` and `prompt` with the receipt's tokens and +/// `prefix_tokens`, the tokens of the cached prefix the turn continued, as +/// the node opened them. An error is the client's own model failing to turn +/// tokens into text. +pub(crate) fn check_tokens( + model: &dyn ClaimedModel, + receipt: &Receipt, + prefix_tokens: &[i32], + prompt: &str, + reply: &ChatReply, +) -> Result { + let split = receipt + .generation_start + .saturating_sub(receipt.position_start) as usize; + let mut sampled = receipt.sampled_tokens(); + while let Some(&last) = sampled.last() { + if !model.is_end_of_generation(last)? { + break; + } + sampled.pop(); + } + let generated = model.detokenize(&sampled)?; + let answered = format!("{}{}", reply.reasoning, reply.content); + let turn_tokens = receipt.tokens.get(..split).unwrap_or(&receipt.tokens); + // every position before the turn must be there to be compared + let found = if prefix_tokens.len() == receipt.position_start as usize { + let prefix_text = model.detokenize(prefix_tokens)?; + find_prompt(&prefix_text, &model.detokenize(turn_tokens)?, prompt) + } else { + PromptMatch::Missing + }; + Ok(TokenOutput { + response_ok: response_matches(&generated, &answered, reply.cut_short), + prompt_ok: found != PromptMatch::Missing, + prompt_compared: found.describe().to_owned(), + generated, + }) +} + +/// Text compared without whitespace and reasoning markers. +fn comparable(text: &str) -> String { + text.replace("", "") + .replace("", "") + .chars() + .filter(|c| !c.is_whitespace()) + .collect() +} + +fn response_matches(generated: &str, answered: &str, cut_short: bool) -> bool { + let (generated, answered) = (comparable(generated), comparable(answered)); + if !cut_short { + return generated == answered; + } + generated + .strip_prefix(answered.as_str()) + .is_some_and(held_back) +} + +/// Whether `tail`, the end of the sampled tokens' text, is what a node +/// holds back from a response it cut: nothing, a character whose bytes it +/// did not finish (which reads as replacement characters), or the start of +/// a marker. +fn held_back(tail: &str) -> bool { + let unfinished = tail.chars().all(|c| c == char::REPLACEMENT_CHARACTER); + let marker = tail.starts_with('<'); + (unfinished || marker) && tail.chars().count() <= CUT_TAIL_CHARS +} + +#[cfg(test)] +mod tests { + use skippy_receipts::glue::GlueEvaluator; + use skippy_receipts::toy_turn::Turn; + + use super::*; + use crate::claimed_model::CacheTypes; + + #[test] + fn the_response_must_be_all_of_the_generated_text() { + let whole = |generated, answered| response_matches(generated, answered, false); + assert!(whole("\nhm\n\n\nParis.", "hmParis.")); + assert!(whole("Paris is big.", " Paris is big. ")); + // dropped, added or empty text fails + assert!(!whole("Paris is big.", "Paris")); + assert!(!whole("Paris.", "Paris. Buy now.")); + assert!(!whole("Paris.", "")); + assert!(whole("", "")); + // a character the node did not finish is not text it left out + assert!(!whole("Paris est gai\u{fffd}", "Paris est gai")); + } + + #[test] + fn a_response_cut_at_the_token_limit_is_the_start_of_the_generated_text() { + let cut = |generated, answered| response_matches(generated, answered, true); + // the last token was half of a character, which the node held back + assert!(cut("Paris est gai\u{fffd}", "Paris est gai")); + // or the start of the marker that ends the reasoning + assert!(cut("\nhm `. + struct Numbered; + + impl ClaimedModel for Numbered { + fn with_layer( + &self, + _: u32, + _: CacheTypes, + _: &mut dyn FnMut(&dyn GlueEvaluator) -> Result<()>, + ) -> Result<()> { + anyhow::bail!("no layers") + } + + fn detokenize(&self, tokens: &[i32]) -> Result { + Ok(tokens.iter().map(|t| format!("<{t}>")).collect()) + } + + fn tokenize(&self, text: &str) -> Result> { + // a text of tokens, each written `` + text.split_terminator('>') + .map(|token| Ok(token.trim_start_matches('<').parse()?)) + .collect() + } + + fn token_piece(&self, token: i32) -> Result> { + Ok(format!("<{token}>").into_bytes()) + } + + fn is_end_of_generation(&self, _: i32) -> Result { + Ok(false) + } + + fn runtime(&self) -> String { + String::new() + } + } + + fn reply(receipt: &Receipt) -> ChatReply { + ChatReply { + model: String::new(), + content: Numbered.detokenize(&receipt.sampled_tokens()).unwrap(), + reasoning: String::new(), + cut_short: false, + } + } + + #[test] + fn the_prompt_is_checked_for_a_turn_from_position_zero() { + let receipt = Turn::new().receipt; + let reply = reply(&receipt); + let checked = check_tokens(&Numbered, &receipt, &[], "<1><2><3>", &reply).unwrap(); + assert!(checked.response_ok); + assert!(checked.prompt_ok); + let other = check_tokens(&Numbered, &receipt, &[], "<7><7>", &reply).unwrap(); + assert!(!other.prompt_ok); + } + + #[test] + fn the_prompt_of_a_turn_that_continued_a_cached_prefix_spans_the_prefix() { + // The receipt holds the end of the prompt alone: tokens 1, 2 and 3. + // The node opens the 40 tokens before them with its answer. + let receipt = Turn::starting_at(40).receipt; + let reply = reply(&receipt); + let prefix: Vec = (0..40).map(|p| 1 + p % 3).collect(); + let check = |prefix: &[i32], prompt: &str| { + let checked = check_tokens(&Numbered, &receipt, prefix, prompt, &reply).unwrap(); + assert!(checked.response_ok); + checked.prompt_ok + }; + // the end of the prefix and the start of the turn, as one text + assert!(check(&prefix, "<2><3><1><1><2><3>")); + assert!(check(&prefix, "<1><2><3>")); + assert!(!check(&prefix, "a prompt the node never saw")); + // a prompt the node cut the start of is not in the tokens + assert!(!check(&prefix, "<9><1><2><3>")); + // without the tokens of the prefix the prompt cannot be found + assert!(!check(&[], "<1><2><3>")); + assert!(!check(&prefix[..39], "<1><2><3>")); + } + + #[test] + fn a_short_message_must_end_in_the_turn_not_anywhere_in_its_prefix() { + let receipt = Turn::starting_at(40).receipt; + let reply = reply(&receipt); + let found = |prefix: &[i32], prompt: &str| { + let checked = check_tokens(&Numbered, &receipt, prefix, prompt, &reply).unwrap(); + (checked.prompt_ok, checked.prompt_compared) + }; + // an earlier turn said "<9>": a message found there is not the one + // this turn read + let mut prefix: Vec = (0..40).map(|p| 1000 + p).collect(); + prefix[2] = 9; + let (ok, compared) = found(&prefix, "<9>"); + assert!(!ok, "{compared}"); + assert_eq!(compared, PromptMatch::Missing.describe()); + // the message that ends in the turn's own tokens is + let (ok, compared) = found(&prefix, "<1039><1><2>"); + assert!(ok); + assert_eq!(compared, PromptMatch::Turn.describe()); + // a request sent again: the prefix holds the message, and the turn + // only the template's closing text + prefix[39] = 9; + let (ok, compared) = found(&prefix, "<9>"); + assert!(ok); + assert_eq!(compared, PromptMatch::PrefixEnd.describe()); + } +} diff --git a/crates/skippy-receipt-audit/src/turn_audit.rs b/crates/skippy-receipt-audit/src/turn_audit.rs new file mode 100644 index 00000000..93cd105b --- /dev/null +++ b/crates/skippy-receipt-audit/src/turn_audit.rs @@ -0,0 +1,489 @@ +//! The audit of one turn a client received: its binding, the challenge the +//! VRF of its root draws, the node's opening, and every check of the opened +//! values against the claimed GGUF. `skippy audit-receipt` runs it on a +//! turn it asked for; a Mesh node runs it on turns its peers served. +//! +//! An audit ends one of four ways ([`Outcome`]), and which one depends on +//! who stopped it: +//! +//! - Before the challenge, the client decides from the receipt alone +//! whether it can audit the turn at all. A receipt it cannot audit is no +//! audit. A receipt that is not bound to its key and signed, does not +//! describe a turn of the claimed model, or contradicts the request, is +//! a failure. +//! - A node that gives no usable signed answer to the challenge, or to the +//! request for attention rows, leaves the audit unanswered. +//! - Once the node signed an answer, every defect of it is a failure, and +//! the evidence shows it. +//! - What then still stops a check is the client's own: the claimed GGUF +//! out of reach, a layer that does not load. That is no audit. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::binding; +use skippy_receipts::challenge; +use skippy_receipts::coverage; +use skippy_receipts::evidence::Evidence; +use skippy_receipts::node_fault::NodeFault; +use skippy_receipts::opened_values::{self, ModelShapes}; +use skippy_receipts::sampler_request::RequestedSampling; +use skippy_receipts::turn::{self, VerifiedBinding}; +use skippy_receipts::vrf; +use skippy_receipts::weights::WeightFile; +use skippy_receipts::wire::{Challenge, Opening, Pick, Receipt}; + +pub use crate::attention_audit::OpenedRows; + +use crate::attention_audit::{self, RowsAnswer}; +use crate::chat_reply::ChatReply; +use crate::claimed_model::{ClaimedModel, LoadClaimedModel}; +use crate::opening_checks::{Checks, check_opening}; +use crate::outcome::{Check, Outcome}; +use crate::output::{AuditOutput, NoAuditOutput, UnansweredOutput}; +use crate::{claimed_file, head_key_file}; + +/// An opening as the node sent it: decoded, its bytes, and the node's +/// signature of them. +pub struct Opened { + pub opening: Opening, + pub bytes: Vec, + pub signature: Option, + pub seconds: f64, +} + +/// Sends a challenge to the node that served the turn. +/// +/// An error from either call means the node gave no usable answer: the +/// request did not get through, timed out, came back with an error status, +/// or its body does not decode. The audit is then unanswered. +pub trait OpenChallenge { + fn open(&self, challenge: &Challenge) -> Result; + /// Asks for the K and V rows of the attention blocks the client drew + /// after the opening. + fn rows(&self, challenge: &BlockChallenge) -> Result; +} + +/// The claimed model, ready to audit turns against. +pub struct ClaimedSetup { + pub weights: WeightFile, + pub model: Box, + /// Executable layers, from the GGUF's metadata. + pub layer_count: u32, + /// The client's head key file for the model. + pub head_key: PathBuf, +} + +impl ClaimedSetup { + /// Opens the claimed GGUF: a file here, or `repo@revision/file` on + /// Hugging Face, read by range into a sparse copy under `cache_root`. + /// A first read of a remote header takes seconds, so this comes before + /// any challenge. + pub fn open(claimed: &Path, cache_root: &Path, load: LoadClaimedModel<'_>) -> Result { + Self::from_file(claimed_file::open(claimed, cache_root)?, load) + } + + /// The claimed model from an opened claimed file. + pub fn from_file( + claimed: claimed_file::ClaimedFile, + load: LoadClaimedModel<'_>, + ) -> Result { + let layer_count = claimed_layer_count(&claimed.path)?; + Ok(Self { + head_key: head_key_file::path_for(&claimed.identity), + weights: claimed.weights, + model: load(claimed.path), + layer_count, + }) + } +} + +/// What the client received in a turn, and what it asked for. +pub struct ReceivedTurn<'a> { + pub receipt: Receipt, + /// The key the request named. + pub key: &'a vrf::SecretKey, + /// The prompt and the reply, when the auditor has them. + pub response: Option<(&'a str, &'a ChatReply)>, + /// The sampling parameters the request set. The node's sampler + /// statement must not contradict them. + pub sampling: RequestedSampling, + /// The id the request asked for the receipt under, when it named one. + pub asked_id: Option<&'a str>, +} + +/// How an audit runs its checks. +pub struct AuditOptions { + /// Challenge this layer alone instead of the ones the VRF picks. + pub layer: Option, + /// Times to compute each challenged layer for the cost report. + pub timing_runs: u32, +} + +impl Default for AuditOptions { + fn default() -> Self { + Self { + layer: None, + timing_runs: 1, + } + } +} + +/// What an audit of a turn found. +pub enum TurnAudit { + /// A check this client cannot run: it says nothing about the node. + NoAudit(NoAuditOutput), + /// The node gave no usable signed answer to the challenge, or to the + /// request for attention rows. Nothing it committed was checked, and + /// that is the node's doing: not a pass, a failure or no audit. + Unanswered(UnansweredOutput), + /// The node answered. The output's outcome is a pass, a failure, or no + /// audit when a check could not run here. + Audited { + output: Box, + /// The signed receipt, the challenge, the opening and both VRF + /// proofs: what `skippy recheck-receipt` checks again. Absent for + /// a challenge picked by hand, which is not evidence. + evidence: Option>, + }, +} + +impl TurnAudit { + pub fn outcome(&self) -> Outcome { + match self { + Self::NoAudit(_) => Outcome::NoAudit, + Self::Unanswered(_) => Outcome::Unanswered, + Self::Audited { output, .. } => output.outcome, + } + } + + fn no_audit(receipt_id: &str, error: &anyhow::Error) -> Self { + Self::NoAudit(NoAuditOutput::new(receipt_id, format!("{error:#}"))) + } +} + +/// Whether the client audits the turn `receipt` records, at `rate`: the VRF +/// of the turn root decides, so the node cannot know in advance. A receipt +/// that is not bound to `key` is never audited. +pub fn audit_drawn(receipt: &Receipt, key: &vrf::SecretKey, rate: f64) -> bool { + turn::verify(receipt, Some(&key.public())).is_ok_and(|bound| { + let (seed, _) = key.evaluate(&turn::challenge_input(&bound.turn_root)); + challenge::audits(&seed, rate) + }) +} + +/// Audits `turn` against the claimed model, opening the challenge with +/// `opener`. +pub fn audit_turn( + setup: &ClaimedSetup, + turn: ReceivedTurn<'_>, + opener: &dyn OpenChallenge, + options: &AuditOptions, +) -> TurnAudit { + let ReceivedTurn { + receipt, + key, + response, + sampling, + asked_id, + } = turn; + let weights = &setup.weights; + // each audit fetches within its own budget, however long the model + // stays open + weights.reset_fetch_budget(); + let model = setup.model.as_ref(); + let id = receipt.receipt_id.clone(); + // a check that cannot run here would fail an honest node; this reads + // the receipt alone, so the node cannot make it true after the challenge + if let Some(reason) = coverage::unauditable(&receipt, weights, &model.runtime()) { + return TurnAudit::NoAudit(NoAuditOutput::new(id, reason)); + } + let content = response.map(|(_, reply)| reply.content.clone()); + let asked = Asked { + sampling: &sampling, + id: asked_id, + }; + // a receipt that is refused is not challenged: there is nothing to ask + let bound = match turn::verify(&receipt, Some(&key.public())) { + Ok(bound) => bound, + Err(error) => { + return refused(content, receipt, |output| { + output.binding_error = Some(format!("{error:#}")); + }); + } + }; + let drawn = fits_claimed_model(weights, setup.layer_count, &receipt) + .and_then(|()| draw_challenge(options.layer, &receipt, setup, key, &bound)); + let challenge = match drawn { + Ok(challenge) => challenge, + Err(error) if NodeFault::find(&error).is_some() => { + return refused(content, receipt, |output| { + output.receipt_error = Some(format!("{error:#}")); + }); + } + Err(error) => return TurnAudit::no_audit(&id, &error), + }; + let request_errors = asked.contradictions(&receipt); + let mut output = AuditOutput::new(content.unwrap_or_default(), receipt, challenge); + output.request_errors = request_errors; + output.hand_picked = options.layer.is_some(); + let opened = match open_signed(opener, &bound, &output.challenge) { + Ok(opened) => opened, + Err(reason) => return unanswered(output, "open", reason), + }; + output.open_seconds = Some(opened.answer.seconds); + // the rows come from the opening exactly as it arrived + let (rows_seed, rows_proof) = key.evaluate(&turn::rows_input(&opened.answer.bytes)); + output.rows_proof = Some(hex::encode(rows_proof)); + let mut evidence = (!output.hand_picked).then(|| { + Evidence::new( + output.receipt.clone(), + output.challenge.clone(), + &opened.answer.bytes, + opened.signature.clone(), + &rows_proof, + ) + }); + let (receipt, challenge) = (output.receipt.clone(), output.challenge.clone()); + let validated = binding::verify_paths(&receipt, &challenge, &opened.answer.opening) + .and_then(|verified| opened_values::validate(verified, weights)); + let validated = match validated { + Ok(validated) => validated, + Err(error) if NodeFault::find(&error).is_some() => { + output.opening_error = Some(format!("{error:#}")); + return audited(output, evidence); + } + Err(error) => return TurnAudit::no_audit(&id, &error), + }; + let checks = Checks { + timing_runs: options.timing_runs, + response, + head_key: Some(setup.head_key.clone()), + }; + let layouts = check_opening(&checks, model, weights, &validated, &rows_seed, &mut output); + note_node_seed(&sampling, &mut output); + let open_rows = |blocks: &BlockChallenge| -> RowsAnswer { + let mut blocks = blocks.clone(); + blocks.proof = Some(hex::encode(rows_proof)); + signed_rows(opener, &bound, &blocks) + }; + let (attention, rows) = + attention_audit::check_attention(&validated, &layouts, &rows_seed, &open_rows); + output.attention = Some(attention); + if let Some(rows) = rows { + evidence = evidence.map(|evidence| evidence.with_rows(&rows.bytes, rows.signature)); + } + audited(output, evidence) +} + +/// A draw replayed with a seed the request did not set shows that the node +/// followed the seed it states, and not that it had no choice of seed: the +/// report says so. +fn note_node_seed(sampling: &RequestedSampling, output: &mut AuditOutput) { + let replayed = matches!( + &output.head, + Some(Check::Verdict(head)) if head.positions.iter().any(|p| p.draw.is_some()) + ); + if replayed && sampling.client_seed().is_none() { + output.notes.push( + "the request set no seed: the draws were replayed with the seed the node chose".into(), + ); + } +} + +/// Adds the checks up. An audit that failed nothing and whose rows request +/// went unanswered is unanswered. +fn audited(mut output: AuditOutput, evidence: Option) -> TurnAudit { + output.finish(); + let unanswered = output + .attention + .as_ref() + .and_then(|a| a.rows_unanswered.clone()); + match (output.outcome, unanswered) { + (Outcome::Unanswered, Some(reason)) => TurnAudit::Unanswered(UnansweredOutput::new( + output.receipt.receipt_id, + "rows", + reason, + )), + _ => TurnAudit::Audited { + output: Box::new(output), + evidence: evidence.map(Box::new), + }, + } +} + +/// A node that did not answer `request`. When the receipt already +/// contradicts the request, that failure stands. +fn unanswered(mut output: AuditOutput, request: &'static str, reason: String) -> TurnAudit { + if output.request_errors.is_empty() { + return TurnAudit::Unanswered(UnansweredOutput::new( + output.receipt.receipt_id, + request, + reason, + )); + } + output.notes.push(format!( + "the node did not answer /receipts/{request}: {reason}" + )); + audited(output, None) +} + +/// A receipt the audit refuses before any challenge, with what `record` +/// says of it: a failure with nothing asked and nothing opened. +fn refused( + content: Option, + receipt: Receipt, + record: impl FnOnce(&mut AuditOutput), +) -> TurnAudit { + let nothing_asked = Challenge { + receipt_id: receipt.receipt_id.clone(), + picks: Vec::new(), + proof: None, + head: Vec::new(), + attention: Vec::new(), + }; + let mut output = AuditOutput::new(content.unwrap_or_default(), receipt, nothing_asked); + record(&mut output); + audited(output, None) +} + +/// What the client asked for besides the turn. +struct Asked<'a> { + sampling: &'a RequestedSampling, + id: Option<&'a str>, +} + +impl Asked<'_> { + /// How the receipt contradicts the request: it is for another id, or + /// its sampler statement does not fit the parameters the client set. + fn contradictions(&self, receipt: &Receipt) -> Vec { + let mut found = Vec::new(); + if let Some(id) = self.id.filter(|id| *id != receipt.receipt_id) { + found.push(format!( + "the receipt is for request {:?}; the client asked under {id:?}", + receipt.receipt_id + )); + } + let sampler = receipt.binding.as_ref().map(|b| b.sampler.as_str()); + found.extend(sampler.and_then(|sampler| self.sampling.contradiction(sampler))); + found + } +} + +/// Checks that a receipt the node signed describes a turn of the claimed +/// model, before anything is asked of the node: its stages, positions and +/// cached prefix, and every token it names is one the model embeds, and +/// its sampler statement has the form an honest node writes. +/// +/// An error that blames the node refuses the receipt. Any other is the +/// client's: its claimed GGUF does not name the model's shapes. +pub(crate) fn fits_claimed_model( + weights: &WeightFile, + layer_count: u32, + receipt: &Receipt, +) -> Result<()> { + binding::verify_shape(receipt, layer_count)?; + if let Some(bound) = receipt.binding.as_ref() { + skippy_receipts::head::sampling::check_statement(&bound.sampler)?; + } + let shapes = ModelShapes::of(weights)?; + opened_values::check_tokens(receipt, &shapes) +} + +/// An opening the node signed for the challenge. +struct SignedOpening { + /// The answer as it arrived. + answer: Opened, + /// The node's signature of it, which verified. + signature: String, +} + +/// Asks the node to open `challenge`. An error is why its answer is not +/// one the node can be held to: none came, or it is not signed for this +/// challenge. +fn open_signed( + opener: &dyn OpenChallenge, + bound: &VerifiedBinding, + challenge: &Challenge, +) -> Result { + let answer = opener.open(challenge).map_err(|e| format!("{e:#}"))?; + let signature = answer + .signature + .clone() + .ok_or("the node did not sign its opening")?; + turn::verify_opening(bound, challenge, &answer.bytes, &signature) + .map_err(|e| format!("{e:#}"))?; + Ok(SignedOpening { answer, signature }) +} + +/// Asks the node for the rows of `blocks`. +fn signed_rows( + opener: &dyn OpenChallenge, + bound: &VerifiedBinding, + blocks: &BlockChallenge, +) -> RowsAnswer { + let rows = match opener.rows(blocks) { + Ok(rows) => rows, + Err(error) => return RowsAnswer::Unanswered(format!("{error:#}")), + }; + let Some(signature) = rows.signature.as_deref() else { + return RowsAnswer::Unanswered("the node did not sign its attention rows".into()); + }; + match turn::verify_rows(bound, blocks, &rows.bytes, signature) { + Ok(()) => RowsAnswer::Signed(rows), + Err(error) => RowsAnswer::Unanswered(format!("{error:#}")), + } +} + +/// Executable layers of a claimed GGUF, from its metadata: a stage plan +/// covers these and never a next-token prediction layer. +pub fn claimed_layer_count(claimed_model: &std::path::Path) -> Result { + let meta = skippy_model_artifact::gguf::scan_gguf_compact_meta(claimed_model) + .with_context(|| format!("read GGUF metadata {}", claimed_model.display()))?; + meta.executable_layer_count() + .context("the claimed GGUF names no executable layers") +} + +/// Weight bytes of each executable layer, which a challenge draws from. +pub(crate) fn executable_layer_bytes(weights: &WeightFile, layer_count: u32) -> BTreeMap { + weights + .layer_bytes() + .into_iter() + .filter(|(layer, _)| *layer < layer_count) + .collect() +} + +/// The challenge the VRF of the turn root picks, with its proof. +fn draw_challenge( + layer: Option, + receipt: &Receipt, + setup: &ClaimedSetup, + key: &vrf::SecretKey, + bound: &VerifiedBinding, +) -> Result { + let layer_bytes = executable_layer_bytes(&setup.weights, setup.layer_count); + let (seed, proof) = key.evaluate(&turn::challenge_input(&bound.turn_root)); + let mut challenge = challenge::draw(receipt, &layer_bytes, &seed)?; + challenge.proof = Some(hex::encode(proof)); + if let Some(layer) = layer { + if layer >= setup.layer_count { + bail!( + "layer {layer} is not one of the model's {} layers", + setup.layer_count + ); + } + let positions = challenge + .picks + .first() + .map(|pick| pick.positions.clone()) + .context("the challenge picks no layer")?; + challenge.picks = vec![Pick { layer, positions }]; + challenge.attention = challenge::draw_attention(&challenge.picks, &seed); + } + Ok(challenge) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipt-audit/src/turn_audit/tests.rs b/crates/skippy-receipt-audit/src/turn_audit/tests.rs new file mode 100644 index 00000000..3cd30375 --- /dev/null +++ b/crates/skippy-receipt-audit/src/turn_audit/tests.rs @@ -0,0 +1,1109 @@ +//! Whole audits of a toy turn: an honest node, and each way a node or this +//! machine can stop one. + +use anyhow::bail; +use skippy_receipts::glue::GlueEvaluator; +use skippy_receipts::toy_turn::{self, LAYERS, RUNTIME, ToyModel, Turn}; +use skippy_receipts::wire::encode_f32; + +use super::*; +use crate::claimed_model::CacheTypes; +use crate::outcome::Check; +use crate::output::HeadOutput; +use crate::recheck::recheck_evidence; + +/// The toy model as the audit loads it. Its token `n` is the text ``. +struct ToyClaimed { + /// No layer loads, as when the native runtime cannot open the GGUF. + unloadable: bool, +} + +impl ClaimedModel for ToyClaimed { + fn with_layer( + &self, + _: u32, + _: CacheTypes, + check: &mut dyn FnMut(&dyn GlueEvaluator) -> Result<()>, + ) -> Result<()> { + if self.unloadable { + bail!("the layer did not load"); + } + check(&ToyModel) + } + + fn detokenize(&self, tokens: &[i32]) -> Result { + Ok(tokens.iter().map(|t| format!("<{t}>")).collect()) + } + + fn tokenize(&self, text: &str) -> Result> { + // a text of tokens, each written `` + text.split_terminator('>') + .map(|token| Ok(token.trim_start_matches('<').parse()?)) + .collect() + } + + fn token_piece(&self, token: i32) -> Result> { + Ok(format!("<{token}>").into_bytes()) + } + + fn is_end_of_generation(&self, _: i32) -> Result { + Ok(false) + } + + fn runtime(&self) -> String { + RUNTIME.to_owned() + } +} + +/// What a node changes in the opening it committed to. +type Change = Box; + +/// What the toy node does with a challenge. +enum Answer { + Honest, + /// The request does not get through. + Refused, + /// The opening comes without a signature. + Unsigned, + /// The signature is of other bytes. + Missigned, + /// The node opens this instead of what it committed, and signs it. + Changed(Change), +} + +struct Node { + turn: Turn, + answer: Answer, +} + +impl OpenChallenge for Node { + fn open(&self, challenge: &Challenge) -> Result { + if matches!(self.answer, Answer::Refused) { + bail!("503 Service Unavailable: the stage cannot replay turns"); + } + let mut opening = self.turn.open(challenge); + if let Answer::Changed(change) = &self.answer { + change(&mut opening); + } + let bytes = serde_json::to_vec(&opening)?; + let signature = match self.answer { + Answer::Unsigned => None, + Answer::Missigned => Some(self.turn.sign_opening(challenge, b"another opening")), + _ => Some(self.turn.sign_opening(challenge, &bytes)), + }; + Ok(Opened { + opening, + bytes, + signature, + seconds: 0.25, + }) + } + + fn rows(&self, _: &BlockChallenge) -> Result { + bail!("the toy model has no attention rows") + } +} + +/// A client of the toy node: its key, its claimed model, and where it +/// keeps its head key. +struct Client { + key: vrf::SecretKey, + setup: ClaimedSetup, + _state: tempfile::TempDir, +} + +impl Client { + fn new() -> Self { + Self::with(toy_turn::weights(), false) + } + + fn with(weights: WeightFile, unloadable: bool) -> Self { + let state = tempfile::tempdir().expect("a temporary directory"); + Self { + key: vrf::SecretKey::from_seed([9; 32]), + setup: ClaimedSetup { + weights, + model: Box::new(ToyClaimed { unloadable }), + layer_count: LAYERS, + head_key: state.path().join("head-key.json"), + }, + _state: state, + } + } + + /// A turn the toy node served this client, greedily. + fn turn(&self) -> Turn { + Turn::new().bound(self.key.public(), turn::GREEDY) + } + + fn audit_with(&self, node: &Node, sampling: RequestedSampling) -> TurnAudit { + let receipt = node.turn.receipt.clone(); + let reply = ChatReply { + model: "toy".into(), + content: ToyClaimed { unloadable: false } + .detokenize(&receipt.sampled_tokens()) + .expect("text"), + reasoning: String::new(), + cut_short: false, + }; + let asked_id = receipt.receipt_id.clone(); + let received = ReceivedTurn { + receipt, + key: &self.key, + response: Some(("<1><2><3>", &reply)), + sampling, + asked_id: Some(&asked_id), + }; + audit_turn(&self.setup, received, node, &AuditOptions::default()) + } + + fn audit(&self, answer: Answer) -> TurnAudit { + let node = Node { + turn: self.turn(), + answer, + }; + self.audit_with(&node, RequestedSampling::greedy()) + } +} + +fn audited(audit: TurnAudit) -> (AuditOutput, Option) { + match audit { + TurnAudit::Audited { output, evidence } => (*output, evidence.map(|e| *e)), + TurnAudit::NoAudit(output) => panic!("no audit: {}", output.reason), + TurnAudit::Unanswered(output) => panic!("unanswered: {}", output.reason), + } +} + +#[test] +fn an_honest_turn_passes_and_its_evidence_rechecks() { + let client = Client::new(); + let audit = client.audit(Answer::Honest); + assert_eq!(audit.outcome(), Outcome::Pass); + assert_eq!(audit.outcome().exit_code(), 0); + let (output, evidence) = audited(audit); + assert!(output.pass, "{}", output.render_text()); + assert!(output.failures.is_empty() && output.unchecked.is_empty()); + assert_eq!(output.layers.len(), LAYERS as usize); + assert!(output.layers.iter().all(|l| l.glue_pass)); + // the router is checked whole, by the auditor's plan + assert!(output.roles.iter().any(|r| r.router && r.pass)); + let head = output.head.as_ref().and_then(Check::verdict).expect("head"); + assert!(head.keyed && head.pass); + assert!(output.render_text().ends_with("AUDIT PASS\n")); + // anyone rechecks the evidence, without the client's key + let evidence = evidence.expect("evidence of a drawn challenge"); + let model = ToyClaimed { unloadable: false }; + let rechecked = recheck_evidence(&evidence, &toy_turn::weights(), &model, LAYERS); + assert_eq!(rechecked.outcome(), Outcome::Pass); + let (rechecked, _) = audited(rechecked); + let head = rechecked + .head + .as_ref() + .and_then(Check::verdict) + .expect("head"); + // it checks the same logits on every row, and judges the same token + assert!(!head.keyed && head.every_row && head.pass); + assert!(head.positions.iter().all(|p| p.logits_ok == Some(true))); +} + +#[test] +fn a_node_that_does_not_answer_the_challenge_leaves_the_audit_unanswered() { + // After it saw the challenge, a node could decline to answer, or + // answer without a signature it can be held to. That was "no audit", + // which costs a node nothing; it is its own outcome now. + let client = Client::new(); + for (answer, reason) in [ + (Answer::Refused, "503 Service Unavailable"), + (Answer::Unsigned, "did not sign its opening"), + (Answer::Missigned, "does not verify"), + ] { + let audit = client.audit(answer); + assert_eq!(audit.outcome(), Outcome::Unanswered, "{reason}"); + assert_eq!(audit.outcome().exit_code(), 3); + let TurnAudit::Unanswered(output) = audit else { + panic!("{reason}: not unanswered"); + }; + assert_eq!(output.request, "open"); + assert!(output.reason.contains(reason), "{}", output.reason); + let json = serde_json::to_value(&output).unwrap(); + assert_eq!(json["outcome"], "unanswered"); + assert_eq!(json["pass"], false); + } +} + +/// The failure a signed opening that `change` altered ends in, and its +/// evidence. +fn defect(change: impl Fn(&mut Opening) + 'static) -> (AuditOutput, Evidence) { + let client = Client::new(); + let audit = client.audit(Answer::Changed(Box::new(change))); + assert_eq!(audit.outcome(), Outcome::Fail); + assert_eq!(audit.outcome().exit_code(), 1); + let (output, evidence) = audited(audit); + assert!(output.unchecked.is_empty(), "{:?}", output.unchecked); + (output, evidence.expect("evidence of the signed opening")) +} + +/// The outcome a recheck of `evidence` ends in. +fn rechecked(evidence: &Evidence) -> AuditOutput { + let model = ToyClaimed { unloadable: false }; + audited(recheck_evidence( + evidence, + &toy_turn::weights(), + &model, + LAYERS, + )) + .0 +} + +#[test] +fn a_decoy_stage_fails_the_audit_and_its_recheck() { + // every check used to run on the decoy, which no Merkle check read + let (output, evidence) = defect(|opening| { + let mut decoy = opening.stages[1].clone(); + decoy.stage_index = 99; + opening.stages.insert(0, decoy); + }); + let error = output.opening_error.as_deref().expect("a refused opening"); + assert!(error.contains("stages [99, 0, 1]"), "{error}"); + assert!(output.provable()); + assert!(output.layers.is_empty(), "no check ran on the decoy"); + let again = rechecked(&evidence); + assert_eq!(again.outcome, Outcome::Fail); + assert_eq!(again.opening_error, output.opening_error); +} + +#[test] +fn a_malformed_signed_opening_is_a_provable_failure_and_not_no_audit() { + // each of these stopped the audit with an error, which was no audit + let nan = encode_f32(&[f32::NAN, 0.0, 0.0, 0.0]); + let short = encode_f32(&[1.0, 2.0]); + let changes: Vec<(&str, Change)> = vec![ + ( + "no matrices", + Box::new(|o| o.stages[0].layers[0].leaves[0].matrices.clear()), + ), + ( + "a short column", + Box::new(move |o| o.stages[0].layers[0].leaves[0].matrices[0].output = short.clone()), + ), + ( + "a value that is not a number", + Box::new(move |o| o.stages[1].layers[0].leaves[0].matrices[1].input = nan.clone()), + ), + ( + "logits of another length", + Box::new(|o| o.stages[1].head[0].logits = Some(encode_f32(&[0.5; 3]))), + ), + ( + "a tensor the GGUF does not have", + Box::new(|o| { + o.stages[0].layers[0].leaves[0].matrices[0].weight = "blk.0.none.weight".into(); + }), + ), + ( + "an expert out of range", + Box::new(|o| { + o.stages[0].layers[0].leaves[0].matrices[2].experts = Some(vec![0, 9]); + }), + ), + ("no stages", Box::new(|o| o.stages.clear())), + ( + "a matmul opened twice", + Box::new(|o| { + let leaf = &mut o.stages[0].layers[0].leaves[0]; + let copy = leaf.matrices[0].clone(); + leaf.matrices.push(copy); + }), + ), + ]; + for (what, change) in changes { + let (output, evidence) = defect(change); + assert!(output.provable(), "{what}: {:?}", output.failures); + let again = rechecked(&evidence); + assert_eq!(again.outcome, Outcome::Fail, "{what}: the recheck differs"); + assert!(again.provable(), "{what}"); + } +} + +#[test] +fn values_a_layer_refuses_fail_it_and_do_not_make_it_no_audit() { + // Matmul outputs and selections are in no leaf, so a node picks them + // after it sees the challenge. The evaluator refused these with an + // error that blamed nobody, so the glue "could not run" and a failing + // layer became no audit. + let changes: Vec<(&str, Change)> = vec![ + ( + "a matmul the layer does not have", + Box::new(|o| { + let leaf = &mut o.stages[0].layers[0].leaves[0]; + let mut extra = leaf.matrices[0].clone(); + extra.index = 7; + leaf.matrices.push(extra); + }), + ), + ( + "two groups of a weight the layer reads once", + Box::new(|o| { + // the toy's `a` is 4 by 4: two groups fit its shape + for leaf in &mut o.stages[0].layers[0].leaves { + leaf.matrices[0].input = encode_f32(&[0.5; 8]); + leaf.matrices[0].output = encode_f32(&[0.25; 8]); + } + }), + ), + ( + "a selection of another length", + Box::new(|o| { + for leaf in &mut o.stages[0].layers[0].leaves { + leaf.selections[0].ids.push(0); + } + }), + ), + ]; + for (what, change) in changes { + let (output, evidence) = defect(change); + assert!(output.provable(), "{what}: {:?}", output.failures); + let glue = &output.layers[0]; + assert!(!glue.glue_pass && glue.glue_error.is_none(), "{what}"); + let again = rechecked(&evidence); + assert_eq!(again.outcome, Outcome::Fail, "{what}: the recheck differs"); + assert!(again.provable(), "{what}"); + } +} + +#[test] +fn a_head_key_that_refused_logits_is_not_used_again() { + // whether a check with the key passes is a bit a node learns about a + // key the client uses for every node of the model + let client = Client::new(); + let key_file = client.setup.head_key.clone(); + assert_eq!(client.audit(Answer::Honest).outcome(), Outcome::Pass); + let kept = std::fs::read(&key_file).expect("the key an audit built"); + assert_eq!(client.audit(Answer::Honest).outcome(), Outcome::Pass); + assert_eq!( + std::fs::read(&key_file).unwrap(), + kept, + "a passing key is kept" + ); + // one logit changed, far past any rounding + let changed = Answer::Changed(Box::new(|opening| { + let head = &mut opening.stages[1].head[0]; + let mut logits = head.logit_values().unwrap().expect("logits"); + logits[0] += 0.5; + head.logits = Some(encode_f32(&logits)); + })); + let (output, evidence) = audited(client.audit(changed)); + assert_eq!(output.outcome, Outcome::Fail); + let head = output.head.as_ref().and_then(Check::verdict).expect("head"); + assert!(head.positions.iter().any(|p| p.logits_ok == Some(false))); + assert!( + !key_file.exists(), + "the key that refused the logits is kept" + ); + // the key is the client's alone, so the audit checked the logits on + // every row as a recheck does: the evidence shows the failure + assert!(output.provable(), "{:?}", output.failures); + assert!(head.every_row && !head.keyed); + let again = rechecked(&evidence.expect("evidence of the signed opening")); + assert_eq!(again.outcome, Outcome::Fail); + assert!(again.provable(), "{:?}", again.failures); + let head = again.head.as_ref().and_then(Check::verdict).expect("head"); + assert!(head.every_row && head.positions.iter().any(|p| p.logits_ok == Some(false))); + // the next audit builds another + assert_eq!(client.audit(Answer::Honest).outcome(), Outcome::Pass); + assert_ne!(std::fs::read(&key_file).unwrap(), kept); +} + +#[test] +fn logits_left_out_fail_the_audit_instead_of_costing_the_client_the_head() { + let (output, evidence) = defect(|opening| { + for head in &mut opening.stages[1].head { + head.logits = None; + } + }); + let fault = output.head.as_ref().and_then(Check::node_fault); + assert!(fault.is_some_and(|f| f.contains("opened no logits"))); + // a recheck judges the token on no other logits, so it finds the same + // defect in the same opening + assert!(output.provable()); + let again = rechecked(&evidence); + assert_eq!(again.outcome, Outcome::Fail); + assert!(again.provable()); + let fault = again.head.as_ref().and_then(Check::node_fault); + assert!(fault.is_some_and(|f| f.contains("opened no logits"))); +} + +#[test] +fn a_cheated_column_fails_its_row_check() { + let (output, evidence) = defect(|opening| { + for leaf in &mut opening.stages[0].layers[0].leaves { + leaf.matrices[0].output = encode_f32(&[9.0, 9.0, 9.0, 9.0]); + } + }); + let failed: Vec<&str> = output.failures.iter().map(|f| f.check.as_str()).collect(); + assert!( + failed + .iter() + .any(|f| f.starts_with("weight rows of a.weight")), + "{failed:?}" + ); + assert_eq!(rechecked(&evidence).outcome, Outcome::Fail); +} + +#[test] +fn a_weight_read_that_fails_is_no_audit() { + // the claimed GGUF's header is at hand and its weights are not: the + // node answered honestly, and nothing it sent is at fault + let client = Client::with(toy_turn::weights_out_of_reach(), false); + let audit = client.audit(Answer::Honest); + assert_eq!(audit.outcome(), Outcome::NoAudit); + assert_eq!(audit.outcome().exit_code(), 2); + let (output, _) = audited(audit); + assert!(output.failures.is_empty(), "{:?}", output.failures); + let out_of_reach = |check: &str| { + output + .unchecked + .iter() + .any(|u| u.starts_with(check) && u.contains("out of reach")) + }; + for check in [ + "glue of layer 0", + "weight rows of layer 1", + "input of layer 0", + "output head", + ] { + assert!(out_of_reach(check), "{check}: {:?}", output.unchecked); + } + assert!(output.render_text().ends_with("NO AUDIT\n")); + assert_eq!( + serde_json::to_value(&output).unwrap()["outcome"], + "no_audit" + ); +} + +#[test] +fn a_layer_that_does_not_load_is_no_audit() { + let client = Client::with(toy_turn::weights(), true); + let audit = client.audit(Answer::Honest); + assert_eq!(audit.outcome(), Outcome::NoAudit); + let (output, _) = audited(audit); + assert!(output.failures.is_empty(), "{:?}", output.failures); + assert!(output.unchecked.iter().any(|u| u.contains("did not load"))); + // the head needs no layer, and its check held + assert!(output.head.as_ref().and_then(Check::verdict).is_some()); + // nor do the weight rows, which are still checked, with no matmul + // taken for a router since the layer's plan is unknown + assert!(output.layers.iter().all(|l| l.matrices.len() == 3)); + assert!(output.roles.iter().all(|r| r.pass && !r.router)); +} + +#[test] +fn a_cheated_column_fails_though_the_layer_does_not_load() { + // a client that cannot evaluate a layer still sees weights that are + // not the claimed ones + let client = Client::with(toy_turn::weights(), true); + let cheated = Answer::Changed(Box::new(|opening| { + for leaf in &mut opening.stages[0].layers[0].leaves { + leaf.matrices[0].output = encode_f32(&[9.0, 9.0, 9.0, 9.0]); + } + })); + let audit = client.audit(cheated); + assert_eq!(audit.outcome(), Outcome::Fail); + let (output, _) = audited(audit); + assert!(output.provable(), "{:?}", output.failures); +} + +#[test] +fn a_receipt_this_verifier_cannot_audit_is_no_audit_before_any_challenge() { + let client = Client::new(); + let mut other_runtime = Turn::new(); + other_runtime.receipt.stages[0].backend = "MTL0".into(); + let node = Node { + turn: other_runtime.bound(client.key.public(), turn::GREEDY), + // the node is never asked + answer: Answer::Refused, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + assert_eq!(audit.outcome(), Outcome::NoAudit); + let TurnAudit::NoAudit(output) = audit else { + panic!("not no audit"); + }; + assert!(output.reason.contains("MTL0"), "{}", output.reason); + assert_eq!( + serde_json::to_value(&output).unwrap()["outcome"], + "no_audit" + ); +} + +#[test] +fn a_receipt_from_a_quantized_kv_cache_is_no_audit_and_never_a_failure() { + // An honest stage with a q8_0 cache fails the loose attention check, so + // a node that still issues such a receipt, as one built before the + // stage refused did, is not audited. + for quantized in ["q8_0", "q4_0"] { + let client = Client::new(); + let mut turn = Turn::new(); + turn.receipt.stages[0].cache_types = vec![quantized.into()]; + let node = Node { + turn: turn.bound(client.key.public(), turn::GREEDY), + // the node is never asked + answer: Answer::Refused, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + assert_eq!(audit.outcome(), Outcome::NoAudit, "{quantized}"); + let TurnAudit::NoAudit(output) = audit else { + panic!("not no audit"); + }; + assert!(output.reason.contains(quantized), "{}", output.reason); + assert!( + output.reason.contains("quantized"), + "{quantized}: {}", + output.reason + ); + } +} + +#[test] +fn a_sampler_statement_that_contradicts_the_request_fails() { + // The statement is the node's own text. One that names a grammar, a + // penalty or a bias leaves its tokens unjudged or moves any token into + // the candidates; the client asked for none of them. + let client = Client::new(); + let statement = turn::sampled(&serde_json::json!({ + "seed": 0, "samplers": ["top_k", "temperature"], "temperature": 0.0, "top_k": 40, + "logit_bias": [[5, 0.0]], "grammar": null, "reasoning_budget": null, + })); + let node = Node { + turn: Turn::new().bound(client.key.public(), &statement), + answer: Answer::Honest, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + assert_eq!(audit.outcome(), Outcome::Fail); + let (output, _) = audited(audit); + assert_eq!(output.request_errors.len(), 1); + assert!( + output.request_errors[0].contains("logit biases"), + "{:?}", + output.request_errors + ); + // the request is not in the evidence: no one else can see this + assert!(!output.provable()); + // a client that does not know what was sent cannot contradict it + let audit = client.audit_with(&node, RequestedSampling::default()); + let (output, _) = audited(audit); + assert!(output.request_errors.is_empty()); +} + +#[test] +fn a_receipt_under_another_id_than_the_request_fails() { + let client = Client::new(); + let node = Node { + turn: client.turn(), + answer: Answer::Honest, + }; + let receipt = node.turn.receipt.clone(); + let received = ReceivedTurn { + receipt, + key: &client.key, + response: None, + sampling: RequestedSampling::greedy(), + asked_id: Some("the id the client sent"), + }; + let audit = audit_turn(&client.setup, received, &node, &AuditOptions::default()); + let (output, _) = audited(audit); + assert_eq!(output.outcome, Outcome::Fail); + assert!(output.request_errors[0].contains("the id the client sent")); + assert!(!output.provable()); +} + +#[test] +fn a_receipt_bound_to_another_key_is_refused_without_a_challenge() { + let client = Client::new(); + let other = vrf::SecretKey::from_seed([1; 32]); + let node = Node { + turn: Turn::new().bound(other.public(), turn::GREEDY), + answer: Answer::Refused, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + assert_eq!(audit.outcome(), Outcome::Fail); + let (output, evidence) = audited(audit); + assert!(output.binding_error.is_some()); + assert!(output.challenge.picks.is_empty()); + assert!(evidence.is_none() && !output.provable()); +} + +#[test] +fn a_turn_that_continued_a_cached_prefix_is_audited_with_its_prefix() { + let client = Client::new(); + let node = Node { + turn: Turn::starting_at(40).bound(client.key.public(), turn::GREEDY), + answer: Answer::Honest, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + let (output, evidence) = audited(audit); + assert_eq!(output.outcome, Outcome::Pass, "{}", output.render_text()); + // the challenge picks positions of the prefix, in every layer + let prefix = output.challenge.prefix_positions(40); + assert_eq!(prefix.len(), skippy_receipts::challenge::PREFIX_POSITIONS); + for layer in &output.layers { + assert!(layer.glue_pass, "{}", output.render_text()); + } + // the prompt is in the tokens of the prefix and the turn together + let tokens = output.tokens.as_ref().and_then(Check::verdict).unwrap(); + assert!(tokens.prompt_ok); + assert!(output.notes.is_empty(), "{:?}", output.notes); + // anyone gets the same verdict from the evidence + let evidence = evidence.expect("a pass of a bound receipt keeps evidence"); + let rechecked = recheck_evidence( + &evidence, + &client.setup.weights, + client.setup.model.as_ref(), + LAYERS, + ); + assert_eq!(rechecked.outcome(), Outcome::Pass); + // a receipt that names a prefix its stages do not commit is refused + let mut uncommitted = Turn::starting_at(40); + uncommitted.receipt.stages[1].prefix = None; + let node = Node { + turn: uncommitted.bound(client.key.public(), turn::GREEDY), + answer: Answer::Refused, + }; + let audit = client.audit_with(&node, RequestedSampling::greedy()); + let (output, _) = audited(audit); + assert!( + output + .receipt_error + .is_some_and(|e| e.contains("cached prefix")) + ); +} + +#[test] +fn a_challenge_picked_by_hand_keeps_no_evidence() { + let client = Client::new(); + let node = Node { + turn: client.turn(), + answer: Answer::Honest, + }; + let received = ReceivedTurn { + receipt: node.turn.receipt.clone(), + key: &client.key, + response: None, + sampling: RequestedSampling::greedy(), + asked_id: None, + }; + let options = AuditOptions { + layer: Some(1), + timing_runs: 1, + }; + let (output, evidence) = audited(audit_turn(&client.setup, received, &node, &options)); + assert!( + output.hand_picked && output.pass, + "{}", + output.render_text() + ); + assert_eq!(output.challenge.picks.len(), 1); + // shown as evidence it would claim the VRF drew what the client chose + assert!(evidence.is_none()); + // a layer the model does not have is the client's mistake, not an + // unanswered challenge + let received = ReceivedTurn { + receipt: node.turn.receipt.clone(), + key: &client.key, + response: None, + sampling: RequestedSampling::greedy(), + asked_id: None, + }; + let options = AuditOptions { + layer: Some(LAYERS), + timing_runs: 1, + }; + let audit = audit_turn(&client.setup, received, &node, &options); + assert_eq!(audit.outcome(), Outcome::NoAudit); +} + +/// The blocks of one attention pick, as a client asks their rows. +fn blocks(turn: &Turn) -> BlockChallenge { + BlockChallenge { + receipt_id: turn.receipt.receipt_id.clone(), + picks: vec![skippy_receipts::attention::opening::BlockPick { + position: 3, + layer: 1, + blocks: vec![0], + }], + proof: Some("ab".into()), + } +} + +/// A node asked for attention rows. +struct RowsNode<'a> { + turn: &'a Turn, + /// What it signs: the rows it sends, other bytes, or nothing. `None` + /// for a node that does not answer. + signs: Option<&'a str>, +} + +const ROWS: &[u8] = br#"{"receipt_id":"toy-turn","stages":[]}"#; + +impl OpenChallenge for RowsNode<'_> { + fn open(&self, _: &Challenge) -> Result { + bail!("not asked") + } + + fn rows(&self, asked: &BlockChallenge) -> Result { + let signature = match self.signs { + None => bail!("the peer did not answer /v1/receipts/rows in time"), + Some("rows") => Some(self.turn.sign_rows(asked, ROWS)), + Some("other blocks") => { + let mut other = asked.clone(); + other.picks[0].blocks = vec![1]; + Some(self.turn.sign_rows(&other, ROWS)) + } + Some(_) => None, + }; + Ok(OpenedRows { + rows: serde_json::from_slice(ROWS)?, + bytes: ROWS.to_vec(), + signature, + seconds: 0.0, + }) + } +} + +#[test] +fn attention_rows_a_node_does_not_send_or_sign_are_unanswered_and_not_a_failure() { + // a failed rows request used to fail the audit while a failed opening + // was no audit; both are the node not answering + let client = Client::new(); + let turn = client.turn(); + let bound = turn::verify(&turn.receipt, None).unwrap(); + let blocks = blocks(&turn); + let answer = |signs| { + let node = RowsNode { turn: &turn, signs }; + signed_rows(&node, &bound, &blocks) + }; + assert!(matches!(answer(Some("rows")), RowsAnswer::Signed(_))); + for (signs, reason) in [ + (None, "did not answer"), + (Some("nothing"), "did not sign its attention rows"), + (Some("other blocks"), "does not verify"), + ] { + let RowsAnswer::Unanswered(why) = answer(signs) else { + panic!("{signs:?}: not unanswered"); + }; + assert!(why.contains(reason), "{why}"); + } +} + +#[test] +fn evidence_without_rows_for_the_drawn_blocks_is_incomplete() { + use crate::recheck::evidence_rows; + let client = Client::new(); + let turn = client.turn(); + let node = Node { + turn: client.turn(), + answer: Answer::Honest, + }; + let (_, evidence) = audited(client.audit_with(&node, RequestedSampling::greedy())); + let evidence = evidence.expect("evidence"); + let layer_bytes = executable_layer_bytes(&client.setup.weights, LAYERS); + let mut asked = blocks(&turn); + asked.proof = None; + // the rows were removed, or never came + let provenance = evidence.verify(&layer_bytes).unwrap(); + let RowsAnswer::Missing(reason) = evidence_rows(&provenance, &asked) else { + panic!("rows from evidence that holds none"); + }; + assert!(reason.contains("holds no attention rows"), "{reason}"); + // rows the node signed for the blocks the seed draws are read + let mut sent = asked.clone(); + sent.proof = Some(evidence.rows_proof.clone()); + let signed = |blocks: &BlockChallenge, rows: &[u8]| { + let with_rows = evidence + .clone() + .with_rows(rows, Some(turn.sign_rows(blocks, rows))); + with_rows.verify(&layer_bytes).unwrap() + }; + let provenance = signed(&sent, ROWS); + assert!(matches!( + evidence_rows(&provenance, &asked), + RowsAnswer::Signed(_) + )); + // rows it signed for other blocks are not evidence of these + let mut other = sent.clone(); + other.picks[0].blocks = vec![1]; + let provenance = signed(&other, ROWS); + assert!(matches!( + evidence_rows(&provenance, &asked), + RowsAnswer::Missing(_) + )); + // rows it signed for these blocks that cannot be read are its defect + let provenance = signed(&sent, b"not rows"); + assert!(matches!( + evidence_rows(&provenance, &asked), + RowsAnswer::Defective(_) + )); +} + +#[test] +fn a_file_that_is_not_evidence_is_no_audit() { + // forged evidence must not read as a failed audit of the node it names + let client = Client::new(); + let (_, evidence) = audited(client.audit(Answer::Honest)); + let mut forged = evidence.expect("evidence"); + forged.challenge.picks.truncate(1); + let model = ToyClaimed { unloadable: false }; + let audit = recheck_evidence(&forged, &toy_turn::weights(), &model, LAYERS); + assert_eq!(audit.outcome(), Outcome::NoAudit); + let TurnAudit::NoAudit(output) = audit else { + panic!("not no audit"); + }; + assert!(output.reason.contains("not evidence"), "{}", output.reason); +} + +/// The sampler statement of a turn sampled at a temperature of 1 with no +/// filter, drawn by the indexed draw of `seed`. +fn drawn_with(seed: u32) -> String { + turn::sampled(&serde_json::json!({ + "seed": seed, "draw": turn::INDEXED_DRAW, + "samplers": ["top_k", "top_p", "min_p", "temperature"], + "temperature": 1.0, "dynatemp_range": 0.0, "top_k": 0, "top_p": 1.0, "min_p": 0.0, + "logit_bias": [], "grammar": null, "reasoning_budget": null, "ignore_eos": false, + "mirostat": { "mode": 0 }, + })) +} + +/// What the request of such a turn set. +fn sampled_request(seed: u32) -> RequestedSampling { + RequestedSampling { + temperature: Some(1.0), + seed: Some(u64::from(seed)), + ..RequestedSampling::greedy() + } +} + +/// The audit of the toy turn when its node says it drew with `seed`. +fn audit_of_seed(client: &Client, seed: u32) -> TurnAudit { + let node = Node { + turn: Turn::new().bound(client.key.public(), &drawn_with(seed)), + answer: Answer::Honest, + }; + client.audit_with(&node, sampled_request(seed)) +} + +fn draws(output: &AuditOutput) -> Vec<(bool, bool)> { + let Some(Check::Verdict(head)) = &output.head else { + panic!("no head verdict"); + }; + head.positions + .iter() + .filter_map(|p| p.draw.as_ref().map(|d| (d.exact, d.pass))) + .collect() +} + +#[test] +fn a_sampled_turn_passes_only_with_the_seed_its_tokens_follow() { + // The toy turn's tokens are what they are. A seed whose draws pick + // them at every checked position makes the turn an honest sampled one; + // with any other seed the node states a draw its tokens do not follow. + let client = Client::new(); + let mut followed = None; + let mut broken = None; + for seed in 1..2000 { + let audit = audit_of_seed(&client, seed); + match audit.outcome() { + Outcome::Pass if followed.is_none() => followed = Some(audited(audit)), + Outcome::Fail if broken.is_none() => broken = Some(audited(audit)), + _ => {} + } + if followed.is_some() && broken.is_some() { + break; + } + } + let (output, _) = followed.expect("a seed the tokens follow"); + let replayed = draws(&output); + assert!(!replayed.is_empty()); + assert!(replayed.iter().all(|&(_, pass)| pass), "{replayed:?}"); + assert!( + output.notes.iter().all(|n| !n.contains("seed")), + "{:?}", + output.notes + ); + + let (output, evidence) = broken.expect("a seed the tokens do not follow"); + assert!(draws(&output).iter().any(|&(_, pass)| !pass)); + assert_eq!(output.failures.len(), 1, "{:?}", output.failures); + assert!(output.failures[0].check.contains("output head")); + // the statement, the tokens and the opened logits are all the node's, + // and signed: anyone who holds the evidence finds the same failure + assert!(output.provable(), "{:?}", output.failures); + let model = ToyClaimed { unloadable: false }; + let evidence = evidence.expect("evidence"); + let (rechecked, _) = audited(recheck_evidence( + &evidence, + &toy_turn::weights(), + &model, + LAYERS, + )); + assert_eq!(rechecked.outcome, Outcome::Fail); + assert_eq!(draws(&rechecked), draws(&output)); +} + +#[test] +fn a_draw_with_a_seed_the_request_did_not_set_is_noted() { + let client = Client::new(); + let seed = (1..2000) + .find(|&seed| audit_of_seed(&client, seed).outcome() == Outcome::Pass) + .expect("a seed the tokens follow"); + let node = Node { + turn: Turn::new().bound(client.key.public(), &drawn_with(seed)), + answer: Answer::Honest, + }; + // the request named no seed: the node chose this one + let unseeded = RequestedSampling { + seed: None, + ..sampled_request(seed) + }; + let (output, _) = audited(client.audit_with(&node, unseeded)); + assert_eq!(output.outcome, Outcome::Pass); + assert!( + output + .notes + .iter() + .any(|n| n.contains("the seed the node chose")), + "{:?}", + output.notes + ); + // a request that set another seed is contradicted + let (output, _) = audited(client.audit_with(&node, sampled_request(seed + 1))); + assert_eq!(output.outcome, Outcome::Fail); + assert!( + output.request_errors[0].contains("seed"), + "{:?}", + output.request_errors + ); + assert!(!output.provable()); +} + +/// The statement of [`drawn_with`] for a turn with a reasoning budget of +/// no tokens, whose sampler was built from the tags `start` and `end`. +fn drawn_with_budget(seed: u32, start: &str, end: &str) -> String { + let mut parameters = turn::sampler_parameters(&drawn_with(seed)).expect("parameters"); + parameters["reasoning_budget"] = 0.into(); + parameters[turn::REASONING] = serde_json::json!({ + "start": start, "ends": [end], "prefill": "", + }); + turn::sampled(¶meters) +} + +/// The audit of the toy turn when its node says it drew with `seed`, under +/// a reasoning budget whose sampler `statement` names. +fn audit_of_budget(client: &Client, seed: u32, statement: &str) -> TurnAudit { + let node = Node { + turn: Turn::new().bound(client.key.public(), statement), + answer: Answer::Honest, + }; + // the runtime builds a reasoning sampler only for a turn with a + // grammar, which a client that asked for none holds against the node; + // a client that does not know replays it, as a recheck does + let request = RequestedSampling { + reasoning_budget: Some(0), + grammar: None, + ..sampled_request(seed) + }; + client.audit_with(&node, request) +} + +fn head_of(output: &AuditOutput) -> &HeadOutput { + let Some(Check::Verdict(head)) = &output.head else { + panic!("no head verdict"); + }; + head +} + +#[test] +fn a_token_a_reasoning_budget_forced_is_not_judged_by_the_draw_and_the_others_are() { + // The toy turn samples three tokens. A node says the first is the tag + // that starts the reasoning and the second the tag that ends it, with + // a budget of no tokens: the sampler forced the second token, and the + // draw picked the first and the third. + let client = Client::new(); + let sampled = Turn::new().receipt.sampled_tokens(); + let tag = |token: i32| format!("<{token}>"); + let honest = |seed| drawn_with_budget(seed, &tag(sampled[0]), &tag(sampled[1])); + // a seed whose draws pick the first and third token and not the second: + // without the budget the turn fails, with it the turn passes + let seed = (1..20_000) + .find(|&seed| { + audit_of_budget(&client, seed, &honest(seed)).outcome() == Outcome::Pass + && audit_of_seed(&client, seed).outcome() == Outcome::Fail + }) + .expect("a seed the free tokens follow and the forced one does not"); + let (output, _) = audited(audit_of_budget(&client, seed, &honest(seed))); + let head = head_of(&output); + let forced: Vec> = head.positions.iter().map(|p| p.forced).collect(); + assert_eq!(forced, [None, Some(sampled[1]), None]); + // the free tokens were judged by the draw, the forced one was not + assert!(head.positions[0].draw.as_ref().is_some_and(|d| d.pass)); + assert!(head.positions[1].draw.is_none() && head.positions[1].judged); + assert!(head.positions[2].draw.as_ref().is_some_and(|d| d.pass)); + let reasoning = head.reasoning.as_ref().expect("the stated sampler"); + assert_eq!((reasoning.budget, reasoning.forced), (0, 1)); + assert_eq!(reasoning.start, tag(sampled[0])); + assert!(output.notes.iter().all(|n| !n.contains("not checked"))); + let text = output.render_text(); + assert!( + text.contains("reasoning budget of 0 tokens") && text.contains("forced 1 of the checked"), + "{text}" + ); + + // A node that sampled another token where its sampler forces one: the + // statement, the tokens and the tags are signed, so anyone finds it. + let other = drawn_with_budget(seed, &tag(sampled[0]), &tag(sampled[1] + 1)); + let (output, evidence) = audited(audit_of_budget(&client, seed, &other)); + assert_eq!(output.outcome, Outcome::Fail); + let head = head_of(&output); + assert_eq!(head.positions[1].forced, Some(sampled[1] + 1)); + assert!(!head.positions[1].pass); + assert!(output.provable(), "{:?}", output.failures); + assert!( + output + .render_text() + .contains("the reasoning budget forces token"), + "{}", + output.render_text() + ); + let model = ToyClaimed { unloadable: false }; + let (rechecked, _) = audited(recheck_evidence( + &evidence.expect("evidence"), + &toy_turn::weights(), + &model, + LAYERS, + )); + assert_eq!(rechecked.outcome, Outcome::Fail); + assert_eq!( + head_of(&rechecked).positions[1].forced, + Some(sampled[1] + 1) + ); +} + +#[test] +fn a_reasoning_sampler_stated_outside_the_limits_leaves_the_tokens_unjudged() { + let client = Client::new(); + let long = "x".repeat(4096); + let (output, _) = audited(audit_of_budget( + &client, + 7, + &drawn_with_budget(7, &long, "<1>"), + )); + // the logits are still checked; the tokens are a gap the report names + assert_eq!(output.outcome, Outcome::Pass); + let head = head_of(&output); + assert!(head.positions.iter().all(|p| !p.judged && p.draw.is_none())); + assert!(head.rule.starts_with("not judged"), "{}", head.rule); + assert!(head.reasoning.is_none()); + assert!( + output.notes.iter().any(|n| n.contains("not checked")), + "{:?}", + output.notes + ); +} diff --git a/crates/skippy-receipts/Cargo.toml b/crates/skippy-receipts/Cargo.toml new file mode 100644 index 00000000..caa539b2 --- /dev/null +++ b/crates/skippy-receipts/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "skippy-receipts" +edition.workspace = true +license.workspace = true +version.workspace = true +description = "Verifiable inference receipts for Skippy: commitments, openings, and client-side weight-row audits" +repository = "https://github.com/Mesh-LLM/mesh-llm" +homepage = "https://github.com/Mesh-LLM/mesh-llm" +readme = "README.md" + +[lib] +name = "skippy_receipts" +path = "src/lib.rs" + +[features] +# A toy model and an honest turn of it (`toy_turn`), for tests of the crates +# that audit receipts. +test-support = [] + +[dependencies] +anyhow.workspace = true +base64 = "0.22" +blake3.workspace = true +curve25519-dalek = "5" +ed25519-dalek = "=3.0.0" +half = "2" +hex = "0.4" +rand = "0.10" +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true + +[dev-dependencies] +tempfile = "3" + +[lints] +workspace = true diff --git a/crates/skippy-receipts/README.md b/crates/skippy-receipts/README.md new file mode 100644 index 00000000..dbab4074 --- /dev/null +++ b/crates/skippy-receipts/README.md @@ -0,0 +1,110 @@ +# skippy-receipts + +Verifiable inference receipts for Skippy. A node that serves a turn signs a +commitment to it. A client then audits which model ran. The design is in +[RECEIPTS.md](../../docs/design/RECEIPTS.md) and +[RECEIPTS_GLUE.md](../../docs/design/RECEIPTS_GLUE.md). The feature +is experimental. Its open limitations are in +[Open limitations](../../docs/design/RECEIPTS.md#open-limitations). + +## Layers + +The crate has three layers. Every top-level module is in one of them. + +| Layer | What it holds | What it may use | +|---|---|---| +| Shared | The format of a receipt, and the arithmetic that a node and a client must do the same way | Shared modules | +| Node | What a serving stage runs: record, commit, open by replay | Shared modules | +| Client | What an auditor runs: the checks of an opening, and the reader of the claimed GGUF | Shared and client modules | + +A client module never uses `recorder`, and `recorder` never uses a client +module. Test code may use all three layers. + +[`src/lib.rs`](src/lib.rs) lists the modules of each layer under a +`// Layer:` comment. [`tests/layers.rs`](tests/layers.rs) reads those +comments and every file under `src/`. It fails when a module has a +`crate::` path into a layer that it may not use. To add a module, put its +`mod` line under the comment of its layer. + +### Shared + +| Module | Responsibility | +|---|---| +| `wire` | The JSON shapes of a receipt, a challenge, an opening and a "cannot open" answer. The receipt version | +| `layer_tensors` | The tensors that a stage reports per layer, keyed by layer, kind and index, with no model-specific names | +| `commitment` | Leaf hashes, the digest of the leaves of a position, the leaf of a prefix cell, the digest of the prefix tokens, and the BLAKE3 Merkle tree over the turn of a stage | +| `turn` | The signed turn root, the signatures of an opening and of attention rows, and the VRF inputs | +| `vrf` | ECVRF-EDWARDS25519-SHA512-TAI (RFC 9381) | +| `draw` | Deterministic draws from a VRF output | +| `challenge` | The draw of a challenge, and the check that a challenge is one that a draw makes | +| `attention` | The layout of a layer's attention, the positions and blocks that a query attends to, and the partial of a block. `attention::opening` is what the two sides send for the attention check | +| `ggml_types` | The ids, names and block sizes of the ggml tensor types | +| `dequant` | Reference dequantization of ggml rows in f64 | +| `cache_types` | The types that a stored KV row can be decoded in, the types that an audit covers (f32 and f16, and no quantized cache), and the decoder of such a row | +| `activation_rounding` | How each kernel rounds f32 values before it multiplies them | +| `node_fault` | The mark on an error that a defective value of the node causes. The shared decoders set it. Only a client reads it | + +The node computes attention partials from its own cache rows, and the +client computes them again from the rows that the node opens. Both must +decode and round the values the same way. That is why `dequant`, +`cache_types` and `activation_rounding` are shared. + +### Node + +| Module | Responsibility | +|---|---| +| `recorder` | Hashes the leaves of each ubatch, keeps a replay log per sequence, commits a turn, opens challenged leaves by replay, pins cells, and keeps the openings that it made. For every KV cell it keeps the leaves of the position and the ubatch that wrote it, so it can open a position of a cached prefix | + +### Client + +| Module | Responsibility | +|---|---| +| `coverage` | Decides from a receipt alone whether this verifier can audit it | +| `binding` | Checks a receipt against the claimed model and the request, and an opening against the receipt: its form, its Merkle paths, the stage boundaries, and the leaves and tokens of a cached prefix | +| `opened_values` | Checks every opened value against the shapes of the claimed model before a check reads it | +| `error_bound` | Compares an error with a tolerance so that a value that is not a number fails | +| `weights` | Reads the header and the rows of the claimed GGUF, with limits on every count and size | +| `shards` | Reads a split GGUF as one file | +| `sparse_copy` | A sparse copy of a remote GGUF that fetches by range | +| `claimed_reads` | The bytes of the claimed GGUF that the glue check reads first | +| `audit` | The row checks, the rounding profiles that each backend may use per weight type, the near-tie repair and the fail rule per weight role | +| `glue` | The glue check. It computes each challenged layer on the opened values through a `GlueEvaluator`, and the input of layer 0 from the tokens | +| `attention_check` | The client side of the attention check: the combination of the partials, the blocks that the client picks, the proofs of the opened rows, and the tolerances | +| `head` | The output head check: the opened logits against the claimed output matrix, with the secret head key (`head::key`) or on every row (`head::every_row`), and the sampled tokens on those logits | +| `head::draw` | The replay of the draw of a sampled turn: the uniform of a seed and a position, and the interval of uniforms that pick the sampled token | +| `head::reasoning_budget` | The replay of the reasoning-budget sampler of a turn, from the tags its statement names: which tokens the sampler forced. A port of `common/reasoning-budget.cpp` of the pinned llama.cpp | +| `sampler_request` | Compares the sampler statement of a receipt with the request of the client | +| `recurrent` | The client side of the recurrent check | +| `evidence` | The evidence of an audit, and the check that a file is evidence | + +### Test support + +`toy_turn` is a toy model with one honest turn. It is for the tests of this +crate and of the crates that audit receipts, behind the `test-support` +feature. It uses all three layers. + +## What the crate does not own + +The crate has no native dependency. + +- The native recorder, the replay and the glue evaluation are in the + llama.cpp patch queue and in `skippy-runtime`. +- The `GlueEvaluator` over libllama, the claimed-file cache, the head key + file and the audit of one turn are in `skippy-receipt-audit`. +- The `audit-receipt` and `recheck-receipt` commands are in + `skippy-commands`. +- The serving routes, the receipt retention and the stage connection are + in `skippy-serving`. +- The CLI flags are in `skippy-cli`. + +## Consumers + +| Crate | Layers | What it does | +|---|---|---| +| `skippy-serving` | Shared and node | Records and commits on each stage, and opens challenges. Its tests also use `binding` to check what a stage opened | +| `skippy-receipt-audit` | Shared and client | Audits one received turn against a claimed GGUF, and rechecks evidence | +| `skippy-commands` | Shared and client | Runs `skippy audit-receipt` and `skippy recheck-receipt` through `skippy-receipt-audit` | +| `mesh-llm-host-runtime` | Shared and client | Audits the turns that the peers of a Mesh node serve, through `skippy-receipt-audit` | + +To serve and audit receipts, see +[docs/RECEIPTS.md](../../docs/RECEIPTS.md). diff --git a/crates/skippy-receipts/src/activation_rounding.rs b/crates/skippy-receipts/src/activation_rounding.rs new file mode 100644 index 00000000..3aa706aa --- /dev/null +++ b/crates/skippy-receipts/src/activation_rounding.rs @@ -0,0 +1,257 @@ +//! How a backend rounds f32 values before a kernel multiplies them: the +//! rounding profiles of the matmul activations, by kernel. +//! +//! The client applies a profile to an opened activation before it compares +//! a matmul with the weights of the claimed GGUF ([`crate::audit`]). A +//! node and a client both apply one to q when they compute attention +//! partials for a kernel that rounds q ([`crate::attention`]), so the +//! rounding is the same arithmetic on both sides. + +/// How a backend rounds the f32 activation before it meets the weights. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Profile { + Raw, + F16, + /// Candidate legacy Metal matmul: both weights and activations round to f16. + /// Not admitted by `rounding_profiles` until end-to-end qualification. + F16Weights, + /// Candidate Metal tensor matmul: f16 weights, f32 activations with the low 13 + /// fraction bits discarded (toward zero, not round-to-nearest). + MetalTensor, + /// Rounded to bf16, as CPU bf16 dot products and cuBLAS bf16 do. + Bf16, + /// CUDA `quantize_q8_1` (MMVQ): d = amax/127, q = round(x/d), d stored as f16. + Q8DivHalf, + /// CUDA `quantize_mmq_q8_1` (MMQ): q = round(x·127/amax), d stored as f16 + /// (the layout with sums, for Q4_0). + Q8MulHalf, + /// MMQ for Q4_K and Q5_K: [`Self::Q8MulHalf`], with the minimum applied + /// to the block sum the kernel stores per 32 values (the block's scale + /// times the sum of its quants, as f16), and the weight's scale and + /// minimum rounded to f16 (the MMA kernels). + Q8MulHalfSums, + /// [`Self::Q8MulHalfSums`] with exact weight scales (the dp4a kernels). + Q8MulHalfSumsDp4a, + /// MMQ with d stored as f32 (Q5_0, Q3_K, Q6_K, IQ4_NL, IQ4_XS). + Q8MulF32, + /// MMQ with one f32 d per 64 values (Q2_K). + Q8Mul64F32, + /// CPU `quantize_row_q8_0`: d = amax/127, q = round(x·(1/d)), d stored as f16. + CpuQ8, + /// CPU `quantize_row_q8_K` for the K-quants: per 256 values, with `max` + /// the value of largest magnitude, q = min(127, round_even(x·-127/max)), + /// d = -max/127 stored as f32. + CpuQ8K, +} + +impl Profile { + pub fn name(self) -> &'static str { + match self { + Self::Raw => "raw", + Self::F16 => "f16", + Self::F16Weights => "f16_weights", + Self::MetalTensor => "metal_tensor", + Self::Bf16 => "bf16", + Self::Q8DivHalf => "q8_32_div_dh", + Self::Q8MulHalf => "q8_32_mul_dh", + Self::Q8MulHalfSums => "q8_32_mul_dh_sums", + Self::Q8MulHalfSumsDp4a => "q8_32_mul_dh_sums_dp4a", + Self::Q8MulF32 => "q8_32_mul_d", + Self::Q8Mul64F32 => "q8_64_mul_d", + Self::CpuQ8 => "cpu_q8_0", + Self::CpuQ8K => "cpu_q8_K", + } + } + + /// For the profiles that apply a weight's minimum to block sums of the + /// activation: whether the weight's scales are rounded to f16. + pub(crate) fn block_sums(self) -> Option { + match self { + Self::Q8MulHalfSums => Some(true), + Self::Q8MulHalfSumsDp4a => Some(false), + _ => None, + } + } + + /// The same profile must round weights in both the reference and a + /// near-tie repair; changing only the activation models neither Metal path. + pub(crate) fn weight(self, w: f64) -> f64 { + match self { + Self::F16Weights | Self::MetalTensor => f64::from(half::f16::from_f64(w).to_f32()), + _ => w, + } + } + + pub fn apply(self, x: &[f32]) -> Vec { + match self { + Self::Raw => x.iter().map(|&v| f64::from(v)).collect(), + Self::MetalTensor => x + .iter() + .map(|&v| { + // Preserve non-finite inputs: truncating a NaN payload + // must not turn it into infinity. + let truncated = if v.is_finite() { + f32::from_bits(v.to_bits() & !0x1fff) + } else { + v + }; + f64::from(truncated) + }) + .collect(), + Self::F16 | Self::F16Weights => x + .iter() + .map(|&v| f64::from(half::f16::from_f32(v).to_f32())) + .collect(), + Self::Bf16 => x + .iter() + .map(|&v| f64::from(half::bf16::from_f32(v).to_f32())) + .collect(), + Self::Q8DivHalf | Self::Q8MulHalf | Self::CpuQ8 => quantize_q8_blocks(self, x), + // the MMQ kernels with block sums quantize the activation as + // the ones without + Self::Q8MulHalfSums | Self::Q8MulHalfSumsDp4a => Self::Q8MulHalf.apply(x), + Self::Q8MulF32 => quantize_mul_blocks(x, 32), + Self::Q8Mul64F32 => quantize_mul_blocks(x, 64), + Self::CpuQ8K => quantize_q8_k(x), + } + } +} + +fn quantize_q8_blocks(profile: Profile, x: &[f32]) -> Vec { + let mut out = Vec::with_capacity(x.len()); + for block in x.chunks(32) { + let amax = block.iter().fold(0.0f32, |m, v| m.max(v.abs())); + if amax == 0.0 { + out.extend(std::iter::repeat_n(0.0, block.len())); + continue; + } + let (d, quant): (f32, Box f32>) = match profile { + Profile::Q8DivHalf => { + let d = amax / 127.0; + (d, Box::new(move |v| (v / d).round())) + } + Profile::Q8MulHalf => { + let d_inv = 127.0 / amax; + (1.0 / d_inv, Box::new(move |v| (v * d_inv).round())) + } + _ => { + let d = amax / 127.0; + let id = 1.0 / d; + (d, Box::new(move |v| (v * id).round())) + } + }; + let dd = f64::from(half::f16::from_f32(d).to_f32()); + // a block too small for its scale: the kernel multiplies by a scale + // of 0, and 0 times the infinite steps would not be a number + if dd == 0.0 { + out.extend(std::iter::repeat_n(0.0, block.len())); + continue; + } + out.extend(block.iter().map(|&v| dd * f64::from(quant(v)))); + } + out +} + +/// CUDA MMQ blocks of `block` values with an f32 scale. +fn quantize_mul_blocks(x: &[f32], block: usize) -> Vec { + let mut out = Vec::with_capacity(x.len()); + for values in x.chunks(block) { + let amax = values.iter().fold(0.0f32, |m, v| m.max(v.abs())); + if amax == 0.0 { + out.extend(std::iter::repeat_n(0.0, values.len())); + continue; + } + let d_inv = 127.0 / amax; + let d = f64::from(1.0 / d_inv); + if d == 0.0 { + out.extend(std::iter::repeat_n(0.0, values.len())); + continue; + } + out.extend(values.iter().map(|&v| d * f64::from((v * d_inv).round()))); + } + out +} + +/// CPU `quantize_row_q8_K_ref`, blocks of 256. +fn quantize_q8_k(x: &[f32]) -> Vec { + let mut out = Vec::with_capacity(x.len()); + for values in x.chunks(256) { + let max = values + .iter() + .fold(0.0f32, |m, &v| if v.abs() > m.abs() { v } else { m }); + if max == 0.0 { + out.extend(std::iter::repeat_n(0.0, values.len())); + continue; + } + let iscale = -127.0 / max; + let d = f64::from(1.0 / iscale); + if d == 0.0 { + out.extend(std::iter::repeat_n(0.0, values.len())); + continue; + } + out.extend( + values + .iter() + .map(|&v| d * f64::from((iscale * v).round_ties_even().min(127.0))), + ); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_cpu_k_quant_profile_scales_by_the_largest_value() { + let mut x = vec![0.5f32; 256]; + x[7] = -2.0; + let y = Profile::CpuQ8K.apply(&x); + // d = 2/127; the largest value is exact and 0.5 is 31.75 steps + assert!((y[7] + 2.0).abs() < 1e-6); + assert!((y[0] - 32.0 * 2.0 / 127.0).abs() < 1e-6); + assert_eq!(Profile::CpuQ8K.apply(&[0.0; 256]), vec![0.0; 256]); + // MMQ blocks of 64 share one scale + let mut x = vec![1.0f32; 128]; + x[0] = 4.0; + let y = Profile::Q8Mul64F32.apply(&x); + assert!((y[63] - 32.0 * 4.0 / 127.0).abs() < 1e-6); + assert!((y[64] - 1.0).abs() < 1e-6); + } + + #[test] + fn a_block_too_small_for_its_scale_rounds_to_zeros() { + // the largest magnitude is past 127 / f32::MAX, so 127 / amax is + // infinite; ggml then stores a scale of 0, and the products are 0. + // The profile gave 0 times infinity, which is not a number, and + // failed the column. + let mut x = vec![1e-38f32; 64]; + x[3] = 0.0; + x[9] = -2e-38; + for p in [ + Profile::Q8DivHalf, + Profile::Q8MulHalf, + Profile::CpuQ8, + Profile::Q8MulF32, + Profile::Q8Mul64F32, + Profile::CpuQ8K, + ] { + let y = p.apply(&x); + assert!(y.iter().all(|v| *v == 0.0), "{p:?}: {y:?}"); + } + } + + #[test] + fn q8_profiles_round_to_the_block_grid() { + let x: Vec = (0..32).map(|i| i as f32 / 31.0).collect(); + for p in [Profile::Q8DivHalf, Profile::Q8MulHalf, Profile::CpuQ8] { + let q = p.apply(&x); + assert!((q[31] - 1.0).abs() < 1e-3, "{:?}", p); + assert!( + q.iter() + .zip(&x) + .all(|(a, b)| (a - f64::from(*b)).abs() < 5e-3) + ); + } + } +} diff --git a/crates/skippy-receipts/src/attention.rs b/crates/skippy-receipts/src/attention.rs new file mode 100644 index 00000000..482debb7 --- /dev/null +++ b/crates/skippy-receipts/src/attention.rs @@ -0,0 +1,416 @@ +//! The loose attention check (`docs/design/RECEIPTS.md`, +//! Verification, step 5): the part that the node and the client share. +//! +//! An opened attention output is checked against the committed context +//! without the client reading all of it. The positions a query attends to +//! are cut into blocks of [`BLOCK_POSITIONS`]. For a head, a block's +//! flash-attention partial is its largest logit, the sum of the +//! exponentials of its logits below that, and their sum of values weighted +//! by them. The node commits every head's partials in its opening. The +//! client then draws a head and a few blocks, recomputes those blocks' +//! partials from the committed q, K and V, and checks that all the head's +//! partials combine to the opened output. +//! +//! A node that cut the context computed its output from fewer blocks. Its +//! partials either combine to that output, and then a block it dropped +//! gives a partial the client recomputes differently, or they are the +//! honest ones and do not combine to its output. +//! +//! Partials are a function of the committed values alone, so the node +//! computes them on its CPU, in f64, and the client's recomputation of a +//! block matches them closely. Only the combination is compared loosely, +//! because the node's backend computed the output with its own kernel. +//! +//! This module holds what both sides need for that: how a layer's +//! attention is laid out ([`AttentionLayout`], [`AttentionOp`]), which +//! positions a query attends to and how they are cut into blocks, the +//! partial of a block ([`block_partial`]), and what the two sides send +//! ([`opening`]). The node opens partials and rows in +//! [`crate::recorder`]. The client checks them in +//! [`crate::attention_check`]. + +use anyhow::{Context, Result, bail, ensure}; + +use crate::activation_rounding::Profile; +use crate::node_fault::{ensure_node, node_fault}; +use crate::wire::{MixingKind, TensorOpening}; + +pub mod opening; + +/// Attended positions per block. +pub const BLOCK_POSITIONS: usize = 64; + +/// Which positions a query reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Window { + /// Every earlier position, and its own. + Causal, + /// The last `n` positions up to its own. + Sliding(u32), + /// Earlier positions in its own chunk of `n`. + Chunked(u32), +} + +impl Window { + pub fn attends(self, query: u32, key: u32) -> bool { + if key > query { + return false; + } + match self { + Self::Causal => true, + Self::Sliding(n) => query - key < n, + Self::Chunked(n) => n > 0 && key / n == query / n, + } + } +} + +/// Blocks of a picked head the client recomputes. +pub(crate) const BLOCKS_PER_PICK: usize = 2; + +/// One attention op of a layer as the graph computes it, by the indices +/// of its values among the layer's committed tensors. +#[derive(Clone, Debug, PartialEq)] +pub struct AttentionLayout { + pub layer: u32, + pub op: AttentionOp, + /// q, among the layer's mixing inputs. + pub q_input: u32, + /// K and V rows, among the layer's stored rows. + pub k_store: u32, + pub v_store: u32, + /// The attention output, among the layer's mixing outputs. + pub output: u32, + /// A gate among the layer's mixing inputs that multiplies the + /// attention output, value by value, before it leaves the token-mixing + /// region; the committed output is the gated one. + pub output_gate: Option, +} + +/// An attention op of a layer, or why the check cannot follow it. +pub type AttentionDescriptor = std::result::Result; + +/// The attention op the check follows in a layer described by +/// `descriptors`: `None` for a layer without attention, an error for one +/// the check cannot follow. +pub fn layer_layout(descriptors: &[AttentionDescriptor]) -> Result> { + match descriptors { + [] => Ok(None), + [Ok(layout)] => Ok(Some(layout)), + [Err(reason)] => bail!("{reason}"), + _ => bail!("a layer with {} attention ops", descriptors.len()), + } +} + +/// The positions a query at `position` attends to, in order, when the +/// sequence holds every position from 0. +/// +/// The list has an entry per attended position, and a position is as large +/// as a receipt says. A client checks what the node opened against +/// [`context_len`] before it calls this. +pub(crate) fn context_positions(op: &AttentionOp, position: u32) -> Vec { + let first = match op.window { + Window::Causal => 0, + Window::Sliding(n) => position.saturating_sub(n.saturating_sub(1)), + Window::Chunked(n) if n > 0 => position - position % n, + Window::Chunked(_) => return Vec::new(), + }; + (first..=position) + .filter(|&key| op.window.attends(position, key)) + .collect() +} + +/// How many positions a query at `position` attends to: the length of +/// [`context_positions`], without making the list. +pub(crate) fn context_len(op: &AttentionOp, position: u32) -> u64 { + let upto = u64::from(position) + 1; + match op.window { + Window::Causal => upto, + Window::Sliding(n) => upto.min(u64::from(n)), + Window::Chunked(0) => 0, + Window::Chunked(n) => u64::from(position % n) + 1, + } +} + +impl AttentionLayout { + /// The layer's q at one position, from its opened mixing values. + pub fn q_values(&self, mixing: &[TensorOpening]) -> Result> { + opened_f32(mixing, MixingKind::Input, self.q_input, "q") + } + + /// The layer's attention output at one position. + pub(crate) fn output_values(&self, mixing: &[TensorOpening]) -> Result> { + opened_f32( + mixing, + MixingKind::Output, + self.output, + "the attention output", + ) + } + + /// The gate the attention output is multiplied by at one position, or + /// `None` for an ungated output. + pub(crate) fn gate_values(&self, mixing: &[TensorOpening]) -> Result>> { + self.output_gate + .map(|gate| opened_f32(mixing, MixingKind::Input, gate, "the attention output gate")) + .transpose() + } + + /// The K and V rows of one position from the layer's stored rows, by + /// index, in their cache types. A row that is missing, of a type the + /// auditor does not check, of another length than the layer's heads, or + /// that holds a value that is not a number, is the node's fault. + pub(crate) fn context_row(&self, position: u32, stored: &[(i32, &[u8])]) -> Result { + let op = &self.op; + let read = |index: u32, len: usize| -> Result> { + let Some((ggml_type, bytes)) = stored.get(index as usize) else { + node_fault!("stored row {index} is missing"); + }; + let row = crate::cache_types::decode_row(*ggml_type, bytes)?; + ensure_node!( + row.len() == len, + "stored row {index} holds {} values, the layer's heads {len}", + row.len() + ); + Ok(row) + }; + Ok(ContextRow { + position, + key: read(self.k_store, op.n_head_kv * op.head_dim_k)?, + value: read(self.v_store, op.n_head_kv * op.head_dim_v)?, + }) + } +} + +fn opened_f32( + mixing: &[TensorOpening], + kind: MixingKind, + index: u32, + what: &str, +) -> Result> { + mixing + .iter() + .find(|m| m.kind == kind && m.index == index) + .with_context(|| format!("{what} is not opened"))? + .f32_values()? + .with_context(|| format!("{what} is absent or not f32")) +} + +/// One layer's attention, as the client's own build of the claimed model +/// computes it. +#[derive(Clone, Debug, PartialEq)] +pub struct AttentionOp { + pub n_head: usize, + pub n_head_kv: usize, + pub head_dim_k: usize, + pub head_dim_v: usize, + /// Multiplies q·k. + pub scale: f64, + /// `softcap · tanh(logit / softcap)` when nonzero. + pub softcap: f64, + /// A per-head logit that only adds to the softmax's denominator. + pub sinks: Option>, + pub window: Window, + /// A rotation of the output before it leaves the token-mixing region. + pub output_rotation: Option, + /// How the kernel rounds each head of q before its dot with K, or + /// `None`. + pub q_rounding: Option, +} + +/// Values in one block of a q rounding. +const Q_ROUNDING_BLOCK: usize = 32; + +/// How a kernel that rounds q to `ggml_type` rounds it. The CPU kernel +/// rounds to q8_0 as [`Profile::CpuQ8`] does. The CUDA kernel rounds the +/// scaled q to q8_1 by division, which differs from that by an ulp at most +/// for a value, well inside the combine tolerance. +pub fn q_rounding(ggml_type: u32) -> Result { + match ggml_type { + crate::ggml_types::GGML_Q8_0 => Ok(Profile::CpuQ8), + other => bail!("attention that rounds q to ggml type {other}"), + } +} + +/// A rotation of each head's attention output in chunks of `n` values: +/// value `i` of a chunk becomes `sum_k matrix[i * n + k] * value k`. +/// llama.cpp rotates V before a quantized KV cache stores it, and rotates +/// the output back. +#[derive(Clone, Debug, PartialEq)] +pub struct OutputRotation { + pub n: usize, + pub matrix: Vec, +} + +impl OutputRotation { + /// Rotates `values`, a whole number of chunks, in place. + pub fn apply(&self, values: &mut [f64]) -> Result<()> { + let n = self.n; + ensure!( + n > 0 && self.matrix.len() == n * n && values.len().is_multiple_of(n), + "a rotation of {} values in chunks of {n}", + values.len() + ); + for chunk in values.chunks_mut(n) { + let input = chunk.to_vec(); + for (value, row) in chunk.iter_mut().zip(self.matrix.chunks(n)) { + *value = row + .iter() + .zip(&input) + .map(|(&m, &x)| f64::from(m) * x) + .sum(); + } + } + Ok(()) + } +} + +impl AttentionOp { + pub fn check_shape(&self) -> Result<()> { + ensure!( + self.n_head > 0 + && self.n_head_kv > 0 + && self.n_head.is_multiple_of(self.n_head_kv) + && self.head_dim_k > 0 + && self.head_dim_v > 0, + "attention shape {self:?} is not one the check follows" + ); + if let Some(sinks) = &self.sinks { + ensure!(sinks.len() == self.n_head, "one sink per head"); + } + if let Some(rotation) = &self.output_rotation { + ensure!( + rotation.n > 0 + && self.head_dim_v.is_multiple_of(rotation.n) + && rotation.matrix.len() == rotation.n * rotation.n, + "an output rotation in chunks of {} across heads of {}", + rotation.n, + self.head_dim_v + ); + } + if self.q_rounding.is_some() { + ensure!( + self.head_dim_k.is_multiple_of(Q_ROUNDING_BLOCK), + "q rounded in blocks of {Q_ROUNDING_BLOCK} across heads of {}", + self.head_dim_k + ); + } + Ok(()) + } + + /// Head `head` of q as the kernel takes it into its dots with K. + fn rounded_q(&self, q: &[f32], head: usize) -> Result> { + let q = head_slice(q, head, self.head_dim_k).context("q")?; + Ok(match self.q_rounding { + Some(profile) => profile.apply(q), + None => q.iter().map(|&x| f64::from(x)).collect(), + }) + } + + /// The K and V head that query head `head` reads. + pub(crate) fn kv_head(&self, head: usize) -> usize { + head / (self.n_head / self.n_head_kv) + } + + /// Values in one head's partials: per block, the largest logit, the + /// sum and the weighted values. + pub(crate) fn partial_len(&self) -> usize { + self.head_dim_v + 2 + } + + fn logit(&self, q: &[f64], k: &[f64]) -> f64 { + let dot: f64 = q.iter().zip(k).map(|(&a, &b)| a * b).sum(); + let logit = dot * self.scale; + if self.softcap == 0.0 { + logit + } else { + self.softcap * (logit / self.softcap).tanh() + } + } +} + +/// One attended position's K and V rows, all heads, dequantized from the +/// cache type. +#[derive(Clone, Debug, PartialEq)] +pub struct ContextRow { + pub position: u32, + pub key: Vec, + pub value: Vec, +} + +/// A block's partial for one head: the largest logit, the sum of +/// `exp(logit - max)`, and the values weighted by those exponentials. +pub(crate) fn block_partial( + op: &AttentionOp, + head: usize, + q: &[f32], + rows: &[ContextRow], +) -> Result> { + let g = op.kv_head(head); + let q = op.rounded_q(q, head)?; + let mut logits = Vec::with_capacity(rows.len()); + for row in rows { + let k = head_slice(&row.key, g, op.head_dim_k).context("a K row")?; + logits.push(op.logit(&q, k)); + } + let max = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let mut partial = vec![0.0; op.partial_len()]; + partial[0] = max; + for (row, logit) in rows.iter().zip(logits) { + let weight = (logit - max).exp(); + partial[1] += weight; + let v = head_slice(&row.value, g, op.head_dim_v).context("a V row")?; + for (out, &x) in partial[2..].iter_mut().zip(v) { + *out += weight * x; + } + } + Ok(partial) +} + +/// Every block's partial for one head, block after block, over `context` +/// (the attended positions, in order). +pub(crate) fn head_partials( + op: &AttentionOp, + head: usize, + q: &[f32], + context: &[ContextRow], +) -> Result> { + let mut partials = Vec::with_capacity(blocks(context.len()) * op.partial_len()); + for block in context.chunks(BLOCK_POSITIONS) { + partials.extend(block_partial(op, head, q, block)?.iter().map(|&x| x as f32)); + } + Ok(partials) +} + +/// Blocks over `positions` attended positions. +pub fn blocks(positions: usize) -> usize { + positions.div_ceil(BLOCK_POSITIONS) +} + +/// The positions of block `block` of a context. +pub(crate) fn block_positions(context: &[u32], block: u32) -> impl Iterator + '_ { + context + .chunks(BLOCK_POSITIONS) + .nth(block as usize) + .into_iter() + .flatten() + .copied() +} + +/// The values of head `head` in a column of heads of `dim` values each. +pub(crate) fn head_slice(column: &[T], head: usize, dim: usize) -> Result<&[T]> { + let start = head * dim; + match column.get(start..start + dim) { + Some(slice) => Ok(slice), + None => bail!( + "a column of {} values has no head {head} of {dim}", + column.len() + ), + } +} + +/// A small attention op and its exact attention, for tests. +#[cfg(test)] +pub(crate) mod test_op; + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/attention/opening.rs b/crates/skippy-receipts/src/attention/opening.rs new file mode 100644 index 00000000..da8d9dbf --- /dev/null +++ b/crates/skippy-receipts/src/attention/opening.rs @@ -0,0 +1,221 @@ +//! What the attention check sends: the heads a challenge picks, the +//! partials a stage opens for them, the blocks the client then picks, and +//! the K and V rows a stage opens for those blocks, with proofs that bind +//! them to the receipt. + +use std::time::Duration; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; + +use crate::commitment::{Hash, MixingDigest, ValueDigest}; +use crate::layer_tensors::TensorKind; +use crate::wire::{MixingKind, TensorOpening, decode_f32, encode_f32}; + +/// A head of one challenged position and layer whose attention the client +/// checks. Part of the challenge, so the node opens the head's partials +/// before the client picks the blocks it recomputes. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct AttentionPick { + pub position: u32, + pub layer: u32, + /// The head is this draw modulo the layer's query heads, which only + /// the model knows. + pub head_draw: u32, +} + +/// One head's partials at a picked position, block after block over the +/// positions it attends to: per block, the largest logit, the sum of the +/// exponentials below it and the values they weight +/// ([`super::block_partial`]). +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct AttentionPartials { + pub position: u32, + pub layer: u32, + pub head: u32, + /// Base64 little-endian f32. + pub partials: String, +} + +impl AttentionPartials { + pub fn new(pick: &AttentionPick, head: u32, partials: &[f32]) -> Self { + Self { + position: pick.position, + layer: pick.layer, + head, + partials: encode_f32(partials), + } + } + + pub fn values(&self) -> Result> { + decode_f32(&self.partials).context("decode attention partials") + } +} + +/// The blocks of one picked head the client recomputes, drawn after the +/// partials arrived. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct BlockPick { + pub position: u32, + pub layer: u32, + pub blocks: Vec, +} + +/// How long after its opening a node keeps the rows of a challenged turn, at +/// most. A stage pins the cells of the turn for this long, and a client asks +/// for the rows ([`BlockChallenge`]) within it: the client checks the opening +/// before it asks for the rows. +pub const ROWS_PIN: Duration = Duration::from_secs(30); + +/// The client's second request: the K and V rows of the picked blocks. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct BlockChallenge { + pub receipt_id: String, + pub picks: Vec, + /// Hex VRF proof, under the receipt's client key, of the opening the + /// blocks are drawn from ([`crate::turn::rows_input`]). Required when + /// the receipt names a key: only its client reads the rows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proof: Option, +} + +impl BlockChallenge { + /// Refuses a request for other rows than a draw asks: a pick that is + /// not an attention pick of `challenge`, a pick twice, or more blocks + /// than [`super::BLOCKS_PER_PICK`]. A node checks this before it reads + /// any row. + pub fn check_shape(&self, challenge: &crate::wire::Challenge) -> Result<()> { + if self.receipt_id != challenge.receipt_id { + anyhow::bail!("the rows name another receipt than the challenge"); + } + let mut seen = std::collections::BTreeSet::new(); + for pick in &self.picks { + let asked = challenge + .attention + .iter() + .any(|a| a.position == pick.position && a.layer == pick.layer); + if !asked || !seen.insert((pick.layer, pick.position)) { + anyhow::bail!( + "position {} of layer {} is not one attention pick of the challenge, once", + pick.position, + pick.layer + ); + } + let increasing = pick.blocks.windows(2).all(|pair| pair[0] < pair[1]); + if pick.blocks.len() > super::BLOCKS_PER_PICK || !increasing { + anyhow::bail!( + "position {} of layer {} asks for {} blocks; a draw asks for at most {} in increasing order", + pick.position, + pick.layer, + pick.blocks.len(), + super::BLOCKS_PER_PICK + ); + } + } + Ok(()) + } + + /// A digest of every field, which the node signs with the rows it + /// opens ([`crate::turn::sign_rows`]): rows are evidence only of the + /// blocks the node was asked for. + pub fn digest(&self) -> Hash { + let mut h = blake3::Hasher::new_derive_key("mesh-llm receipts block challenge v1"); + let text = |h: &mut blake3::Hasher, s: &str| { + h.update(&(s.len() as u64).to_le_bytes()); + h.update(s.as_bytes()); + }; + text(&mut h, &self.receipt_id); + h.update(&(self.picks.len() as u64).to_le_bytes()); + for pick in &self.picks { + h.update(&pick.position.to_le_bytes()); + h.update(&pick.layer.to_le_bytes()); + h.update(&(pick.blocks.len() as u64).to_le_bytes()); + for block in &pick.blocks { + h.update(&block.to_le_bytes()); + } + } + match &self.proof { + Some(proof) => { + h.update(&[1]); + text(&mut h, proof); + } + None => { + h.update(&[0]); + } + } + *h.finalize().as_bytes() + } +} + +/// The node's answer: the rows each stage holds. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct RowsOpening { + pub receipt_id: String, + pub stages: Vec, +} + +/// The rows one stage opened, each once however many picks read it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct StageRows { + pub stage_index: u32, + pub rows: Vec, +} + +/// What a stage stored at one attended position of one layer: every +/// stored row of the layer, by index, in the cache's types, and how they +/// are bound. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct RowOpening { + pub position: u32, + pub layer: u32, + pub stored: Vec, + pub proof: RowProof, +} + +/// How an opened row is bound to the receipt. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RowProof { + /// The turn computed the position: the half of its mixing leaf that is + /// not stored rows ([`crate::commitment::mixing_rest`]), and the leaf's + /// path in the stage tree. + Turn { rest: String, path: Vec }, + /// An earlier computation stored it in a cell the turn read: the + /// cell's index, the path of the layer's stored leaf in the cell's + /// digest, the hex digest of the leaves the stage committed at the + /// position ([`crate::commitment::position_digest`]), which the + /// prefix leaf binds with the cell, and the cell's path in the prefix + /// tree. + Prefix { + cell: u32, + cell_path: Vec, + leaves: String, + prefix_path: Vec, + }, +} + +pub(crate) fn parse_hash(text: &str) -> Result { + crate::commitment::hex_array(text, "a hash") +} + +/// The digests of a layer's stored rows, which must be opened in index +/// order. +pub(crate) fn stored_digests(stored: &[TensorOpening]) -> Result> { + stored + .iter() + .enumerate() + .map(|(i, row)| { + ensure!( + row.kind == MixingKind::Stored && row.index as usize == i, + "stored rows must be opened in index order" + ); + Ok(MixingDigest { + kind: TensorKind::MixingStored, + index: row.index, + value: row + .bytes()? + .map(|bytes| (row.ggml_type, ValueDigest::of(&bytes))), + }) + }) + .collect() +} diff --git a/crates/skippy-receipts/src/attention/test_op.rs b/crates/skippy-receipts/src/attention/test_op.rs new file mode 100644 index 00000000..73afcf26 --- /dev/null +++ b/crates/skippy-receipts/src/attention/test_op.rs @@ -0,0 +1,71 @@ +//! A small attention op with a context and a query, and the exact attention +//! of a head over that context, for tests. + +use super::{AttentionOp, ContextRow, Window, head_slice}; + +pub(crate) fn op() -> AttentionOp { + AttentionOp { + n_head: 4, + n_head_kv: 2, + head_dim_k: 3, + head_dim_v: 2, + scale: 0.5, + softcap: 0.0, + sinks: None, + window: Window::Causal, + output_rotation: None, + q_rounding: None, + } +} + +/// A deterministic value in [-1, 1). +pub(crate) fn value(seed: u64) -> f32 { + let x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(17); + (x % 2000) as f32 / 1000.0 - 1.0 +} + +pub(crate) fn context(op: &AttentionOp, n: u32) -> Vec { + (0..n) + .map(|position| ContextRow { + position, + key: (0..op.n_head_kv * op.head_dim_k) + .map(|i| f64::from(value(u64::from(position) * 1000 + i as u64))) + .collect(), + value: (0..op.n_head_kv * op.head_dim_v) + .map(|i| f64::from(value(u64::from(position) * 1000 + 500 + i as u64))) + .collect(), + }) + .collect() +} + +pub(crate) fn query(op: &AttentionOp) -> Vec { + (0..op.n_head * op.head_dim_k) + .map(|i| value(77 + i as u64) * 3.0) + .collect() +} + +/// Plain softmax attention for one head over every row. +pub(crate) fn exact(op: &AttentionOp, head: usize, q: &[f32], rows: &[ContextRow]) -> Vec { + let g = op.kv_head(head); + let q = op.rounded_q(q, head).unwrap(); + let logits: Vec = rows + .iter() + .map(|r| op.logit(&q, head_slice(&r.key, g, op.head_dim_k).unwrap())) + .collect(); + let sink = op + .sinks + .as_ref() + .map_or(f64::NEG_INFINITY, |s| f64::from(s[head])); + let max = logits.iter().copied().fold(sink, f64::max); + let weights: Vec = logits.iter().map(|l| (l - max).exp()).collect(); + let sum: f64 = weights.iter().sum::() + (sink - max).exp(); + (0..op.head_dim_v) + .map(|d| { + rows.iter() + .zip(&weights) + .map(|(r, w)| w * head_slice(&r.value, g, op.head_dim_v).unwrap()[d]) + .sum::() + / sum + }) + .collect() +} diff --git a/crates/skippy-receipts/src/attention/tests.rs b/crates/skippy-receipts/src/attention/tests.rs new file mode 100644 index 00000000..ebae72b2 --- /dev/null +++ b/crates/skippy-receipts/src/attention/tests.rs @@ -0,0 +1,119 @@ +use super::test_op::{context, op, query}; +use super::*; + +#[test] +fn a_head_reads_its_own_kv_head() { + let op = op(); + assert_eq!( + (0..4).map(|h| op.kv_head(h)).collect::>(), + vec![0, 0, 1, 1] + ); +} + +#[test] +fn windows_bound_the_attended_positions() { + assert!(Window::Causal.attends(5, 0)); + assert!(!Window::Causal.attends(5, 6)); + assert!(Window::Sliding(4).attends(5, 2)); + assert!(!Window::Sliding(4).attends(5, 1)); + assert!(Window::Chunked(4).attends(5, 4)); + assert!(!Window::Chunked(4).attends(5, 3)); +} + +#[test] +fn a_rounded_q_enters_the_partials_as_the_kernel_rounds_it() { + let rounded = AttentionOp { + head_dim_k: 32, + q_rounding: Some(q_rounding(8).unwrap()), + ..op() + }; + rounded.check_shape().unwrap(); + let raw = AttentionOp { + q_rounding: None, + ..rounded.clone() + }; + let rows = context(&rounded, 70); + let q = query(&rounded); + let as_kernel: Vec = Profile::CpuQ8.apply(&q).iter().map(|&x| x as f32).collect(); + let partials = |op: &AttentionOp, q: &[f32]| head_partials(op, 1, q, &rows).unwrap(); + assert_eq!(partials(&rounded, &q), partials(&raw, &as_kernel)); + assert_ne!(partials(&rounded, &q), partials(&raw, &q)); + assert!(q_rounding(2).is_err()); + let short = AttentionOp { + q_rounding: Some(Profile::CpuQ8), + ..op() + }; + assert!(short.check_shape().is_err()); +} + +#[test] +fn the_context_length_counts_the_attended_positions() { + // the length is checked against what the node opened before the list + // of positions is made, so the two must agree + let windows = [ + Window::Causal, + Window::Sliding(1), + Window::Sliding(7), + Window::Sliding(0), + Window::Chunked(1), + Window::Chunked(5), + Window::Chunked(0), + ]; + for window in windows { + let op = AttentionOp { window, ..op() }; + for position in 0..40u32 { + let attended: Vec = (0..=position) + .filter(|&key| window.attends(position, key)) + .collect(); + assert_eq!(context_positions(&op, position), attended, "{window:?}"); + assert_eq!(context_len(&op, position), attended.len() as u64); + } + } + // a position as large as a receipt can claim is counted, not listed + let far = u32::MAX - 1; + assert_eq!(context_len(&op(), far), u64::from(far) + 1); + let sliding = AttentionOp { + window: Window::Sliding(64), + ..op() + }; + assert_eq!(context_len(&sliding, far), 64); + assert_eq!(context_positions(&sliding, far).len(), 64); +} + +#[test] +fn a_stored_row_of_another_type_length_or_not_a_number_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + let layout = AttentionLayout { + layer: 0, + op: op(), + q_input: 0, + k_store: 0, + v_store: 1, + output: 0, + output_gate: None, + }; + let f16 = |values: &[f32]| -> Vec { + values + .iter() + .flat_map(|&v| half::f16::from_f32(v).to_le_bytes()) + .collect() + }; + let (k, v) = (f16(&[0.5; 6]), f16(&[0.25; 4])); + let row = layout + .context_row(9, &[(1, k.as_slice()), (1, v.as_slice())]) + .unwrap(); + assert_eq!((row.key.len(), row.value.len()), (6, 4)); + let nan = f16(&[0.5, f32::NAN, 0.5, 0.5, 0.5, 0.5]); + let short = f16(&[0.5; 4]); + let bad: [Vec<(i32, &[u8])>; 5] = [ + vec![(39, &k), (1, &v)], + vec![(3, &k), (1, &v)], + vec![(1, &nan), (1, &v)], + vec![(1, &short), (1, &v)], + vec![(1, &k)], + ]; + for (i, stored) in bad.iter().enumerate() { + let error = layout.context_row(9, stored).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "row {i}: {error:#}"); + } +} diff --git a/crates/skippy-receipts/src/attention_check.rs b/crates/skippy-receipts/src/attention_check.rs new file mode 100644 index 00000000..5c1175d2 --- /dev/null +++ b/crates/skippy-receipts/src/attention_check.rs @@ -0,0 +1,548 @@ +//! The client's side of the loose attention check ([`crate::attention`]): +//! the combination of a head's partials against the opened output, the +//! blocks it then picks, the proofs of the rows the node opens for them, +//! and the recomputation of those blocks' partials. + +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Context, Result, bail, ensure}; + +use crate::attention::opening::{ + AttentionPartials, AttentionPick, BlockChallenge, BlockPick, RowOpening, RowProof, RowsOpening, + parse_hash, stored_digests, +}; +use crate::attention::{ + AttentionLayout, AttentionOp, BLOCK_POSITIONS, BLOCKS_PER_PICK, ContextRow, block_partial, + block_positions, blocks, context_len, context_positions, head_slice, +}; +use crate::commitment::{ + leaf_index, mixing_leaf_from, mixing_slot, prefix_leaf, root_from_path, slots_per_position, + stored_leaf, +}; +use crate::draw::DrawStream; +use crate::error_bound::{all_finite, within, worst, worst_of}; +use crate::node_fault::BlameNode; +use crate::wire::{LeafOpening, Receipt, StageCommitment}; + +/// A recomputed block's partial passes within this error, relative to the +/// partial's own scale. Both sides compute it in f64 from the same values. +pub const PARTIAL_TOLERANCE: f64 = 1e-6; +/// The least error within which the partials' combination passes against +/// the opened output, relative to the output's largest value: the tolerance +/// of a short context ([`combine_tolerance`]). +pub(crate) const COMBINE_TOLERANCE: f64 = 2e-2; +/// How the tolerance grows with the square root of the attended positions. +/// A flash-attention kernel that sums f16 values in f16 (CUDA prefill) +/// rounds each partial sum to 11 bits, and the rounding adds up like a +/// random walk over the context. Honest CUDA prefill was measured at up to +/// `0.54 * 2^-11 * sqrt(positions)` over 163 picks from 3,000 to 31,000 +/// positions (`RECEIPTS_MEASUREMENTS.md`); this is `2 * 2^-11`, about 3.7 +/// times that. +const COMBINE_TOLERANCE_PER_SQRT_POSITION: f64 = 1.0 / 1024.0; + +/// The error within which the partials of a head that attends to `context` +/// positions pass against the opened output: [`COMBINE_TOLERANCE`] up to +/// about 420 positions, then growing with their square root (6.3e-2 at +/// 4,096 positions, 1.8e-1 at 32,768). A fixed tolerance fails honest long +/// turns: at 2e-2 a CUDA node was at 97% of it at 7,000 positions and past +/// it at 19,000. +pub(crate) fn combine_tolerance(context: usize) -> f64 { + COMBINE_TOLERANCE.max(COMBINE_TOLERANCE_PER_SQRT_POSITION * (context as f64).sqrt()) +} + +/// One picked head after the node opened its partials. +#[derive(Clone, Debug)] +pub struct OpenedHead { + pub pick: AttentionPick, + pub head: u32, + pub partials: Vec, + /// The positions the query attends to, in order. + pub context: Vec, + /// How far the partials combine from the opened output. + pub combine_error: f64, +} + +impl OpenedHead { + pub fn passed(&self) -> bool { + within(self.combine_error, self.tolerance()) + } + + /// The combine error this head passes within, for its context. + pub fn tolerance(&self) -> f64 { + combine_tolerance(self.context.len()) + } + + pub fn blocks(&self) -> usize { + blocks(self.context.len()) + } +} + +/// Checks that the partials the node opened for `pick` combine to the +/// output it opened at that position, `leaf`. +/// +/// An error that blames the node ([`crate::node_fault::NodeFault`]) is a +/// defect of what it opened. Any other is an attention shape the check +/// does not follow, which says nothing about the node. +pub fn check_partials( + layout: &AttentionLayout, + pick: &AttentionPick, + leaf: &LeafOpening, + opened: &AttentionPartials, +) -> Result { + let op = &layout.op; + op.check_shape()?; + let head = pick.head_draw % u32::try_from(op.n_head)?; + opened_head(layout, pick, leaf, opened, head).or_node_fault() +} + +/// [`check_partials`] for the model's head `head`, once the auditor's own +/// layout is known to be one the check follows. +fn opened_head( + layout: &AttentionLayout, + pick: &AttentionPick, + leaf: &LeafOpening, + opened: &AttentionPartials, + head: u32, +) -> Result { + let op = &layout.op; + ensure!( + opened.head == head, + "the node opened head {} for draw {}, the model's head is {head}", + opened.head, + pick.head_draw + ); + // the length first: the context is as long as the position is large, + // and only the receipt says how large that is + let attended = context_len(op, pick.position); + let partials = opened.values()?; + let expected = attended.div_ceil(BLOCK_POSITIONS as u64) * op.partial_len() as u64; + ensure!( + partials.len() as u64 == expected, + "{} partial values for {attended} attended positions", + partials.len() + ); + ensure!(all_finite(&partials), "a partial is not a number"); + check_sums(&partials, op.partial_len(), attended)?; + let context = context_positions(op, pick.position); + let output = layout.output_values(&leaf.mixing)?; + let head_index = usize::try_from(head)?; + let output = head_slice(&output, head_index, op.head_dim_v)?; + let mut combined = combine(op, head_index, &partials)?; + if let Some(rotation) = &op.output_rotation { + rotation.apply(&mut combined)?; + } + if let Some(gate) = layout.gate_values(&leaf.mixing)? { + let gate = head_slice(&gate, head_index, op.head_dim_v)?; + for (value, &g) in combined.iter_mut().zip(gate) { + *value *= f64::from(g); + } + } + Ok(OpenedHead { + pick: pick.clone(), + head, + combine_error: combine_error(&combined, output), + partials, + context, + }) +} + +/// Checks what every honest partial holds: its sum of exponentials counts +/// its largest logit once, at `exp(0) = 1`, and no more than one per +/// position of the block. The node sums them in f64 and rounds to f32, +/// which keeps both bounds exact. A partial outside them is no block's. +fn check_sums(partials: &[f32], len: usize, attended: u64) -> Result<()> { + for (b, partial) in partials.chunks(len).enumerate() { + let start = b as u64 * BLOCK_POSITIONS as u64; + let positions = attended.saturating_sub(start).min(BLOCK_POSITIONS as u64) as f32; + let sum = partial[1]; + ensure!( + (1.0..=positions).contains(&sum), + "block {b}'s partial sums its exponentials to {sum}; a block of {positions} \ + positions sums them to 1 to {positions}" + ); + } + Ok(()) +} + +/// The blocks the client recomputes for each opened head, drawn from +/// `seed`, which the node cannot know before it opened the partials. +pub fn block_challenge(receipt_id: &str, heads: &[OpenedHead], seed: &[u8]) -> BlockChallenge { + let picks = heads + .iter() + .map(|h| BlockPick { + position: h.pick.position, + layer: h.pick.layer, + blocks: draw_blocks(seed, &h.pick, &block_masses(&h.partials, h.blocks())), + }) + .collect(); + BlockChallenge { + receipt_id: receipt_id.to_owned(), + picks, + proof: None, + } +} + +/// Each block's share of the softmax, as the node's partials claim it: +/// `exp(max - largest max) * sum`. A block that dominates the combination +/// has most of it. +fn block_masses(partials: &[f32], n_blocks: usize) -> Vec { + let len = partials.len() / n_blocks.max(1); + if len < 2 { + return vec![1.0; n_blocks]; + } + let blocks = partials.chunks(len); + let largest = blocks + .clone() + .map(|p| f64::from(p[0])) + .fold(f64::NEG_INFINITY, f64::max); + blocks + .map(|p| (f64::from(p[0]) - largest).exp() * f64::from(p[1])) + .collect() +} + +/// [`BLOCKS_PER_PICK`] distinct blocks of the `masses.len()` blocks, sorted; +/// every block when there are no more. The first is drawn in proportion to +/// the mass the node's partials claim for each block, so a false block that +/// steers the combination is the one most likely recomputed. The second is +/// drawn uniformly from the others, so a block the partials make small, as +/// one the node dropped, is still drawn. +pub(crate) fn draw_blocks(seed: &[u8], pick: &AttentionPick, masses: &[f64]) -> Vec { + let n = u32::try_from(masses.len()).unwrap_or(u32::MAX); + if masses.len() <= BLOCKS_PER_PICK { + return (0..n).collect(); + } + let label = format!("attention/{}/{}", pick.position, pick.layer); + let mut picked = BTreeSet::from([weighted_block(seed, &label, masses)]); + let mut stream = DrawStream::new(seed, &label); + while picked.len() < BLOCKS_PER_PICK { + picked.insert(stream.in_range(0..n)); + } + picked.into_iter().collect() +} + +/// A block drawn in proportion to `masses`; uniformly when they hold no +/// usable mass. +fn weighted_block(seed: &[u8], label: &str, masses: &[f64]) -> u32 { + let mut stream = DrawStream::new(seed, &format!("{label}/mass")); + let total: f64 = masses.iter().sum(); + let n = u32::try_from(masses.len()).unwrap_or(u32::MAX); + if !(total.is_finite() && total > 0.0) { + return stream.in_range(0..n); + } + let target = stream.unit() * total; + let mut cumulative = 0.0; + for (b, mass) in (0..n).zip(masses) { + cumulative += mass; + if target < cumulative { + return b; + } + } + n - 1 +} + +/// Checks that `opening` holds exactly the rows `blocks` asks of `heads` +/// (one head per pick of `blocks`, in order): one part per stage of the +/// receipt, in order, and every position of every picked block, once. A +/// node that left a row out, sent one twice or added one fails here, so +/// the recomputation reads the rows it asked for and no others. +/// +/// An error is the node's fault. +pub fn verify_answer( + receipt: &Receipt, + blocks: &BlockChallenge, + heads: &[OpenedHead], + opening: &RowsOpening, +) -> Result<()> { + answered_rows(receipt, blocks, heads, opening).or_node_fault() +} + +fn answered_rows( + receipt: &Receipt, + blocks: &BlockChallenge, + heads: &[OpenedHead], + opening: &RowsOpening, +) -> Result<()> { + ensure!( + opening.receipt_id == receipt.receipt_id, + "the rows name another receipt" + ); + let stages: Vec = receipt.stages.iter().map(|s| s.stage_index).collect(); + let opened: Vec = opening.stages.iter().map(|s| s.stage_index).collect(); + ensure!( + opened == stages, + "the rows come from stages {opened:?}; the receipt's stages are {stages:?}" + ); + let mut wanted = BTreeSet::new(); + for (head, pick) in heads.iter().zip(&blocks.picks) { + for &block in &pick.blocks { + wanted.extend(block_positions(&head.context, block).map(|p| (pick.layer, p))); + } + } + let mut seen = BTreeSet::new(); + for row in opening.stages.iter().flat_map(|s| &s.rows) { + let key = (row.layer, row.position); + ensure!( + wanted.contains(&key) && seen.insert(key), + "the row at position {} of layer {} is not one the blocks ask for, once", + row.position, + row.layer + ); + } + if let Some((layer, position)) = wanted.difference(&seen).next() { + bail!("the row at position {position} of layer {layer} is not opened"); + } + Ok(()) +} + +/// The K and V rows of every opened position, by (layer, position), each +/// checked against the receipt. +/// +/// An error is the node's fault. +pub fn verify_rows( + receipt: &Receipt, + layouts: &BTreeMap, + opening: &RowsOpening, +) -> Result> { + committed_rows(receipt, layouts, opening).or_node_fault() +} + +fn committed_rows( + receipt: &Receipt, + layouts: &BTreeMap, + opening: &RowsOpening, +) -> Result> { + ensure!( + opening.receipt_id == receipt.receipt_id, + "the rows name another receipt" + ); + let mut rows = BTreeMap::new(); + for stage_rows in &opening.stages { + let stage = receipt + .stages + .iter() + .find(|s| s.stage_index == stage_rows.stage_index) + .with_context(|| format!("the receipt has no stage {}", stage_rows.stage_index))?; + for row in &stage_rows.rows { + ensure!( + (stage.layer_start..stage.layer_end).contains(&row.layer), + "stage {} opened a row of layer {}", + stage.stage_index, + row.layer + ); + verify_row(receipt, stage, row) + .with_context(|| format!("position {}, layer {}", row.position, row.layer))?; + let layout = layouts + .get(&row.layer) + .with_context(|| format!("layer {} has no attention to check", row.layer))?; + let stored = row + .stored + .iter() + .map(|s| Ok((s.ggml_type, s.bytes()?.context("a stored row is absent")?))) + .collect::>>()?; + let stored: Vec<(i32, &[u8])> = + stored.iter().map(|(t, b)| (*t, b.as_slice())).collect(); + rows.insert( + (row.layer, row.position), + layout.context_row(row.position, &stored)?, + ); + } + } + Ok(rows) +} + +fn verify_row(receipt: &Receipt, stage: &StageCommitment, row: &RowOpening) -> Result<()> { + let stored = stored_leaf(row.position, row.layer, &stored_digests(&row.stored)?); + match &row.proof { + RowProof::Turn { rest, path } => { + ensure!( + (receipt.position_start..receipt.position_end).contains(&row.position), + "the turn did not compute this position" + ); + let leaf = mixing_leaf_from(row.position, row.layer, &parse_hash(rest)?, &stored); + let index = leaf_index( + row.position, + mixing_slot(row.layer, stage.layer_start), + receipt.position_start, + slots_per_position(stage.layer_start, stage.layer_end), + ); + let root = root_from_path(leaf, index, stage.leaf_count, path)?; + ensure!( + hex::encode(root) == stage.root, + "the mixing leaf is not in the stage tree" + ); + } + RowProof::Prefix { + cell, + cell_path, + leaves, + prefix_path, + } => { + let prefix = stage + .prefix + .as_ref() + .context("the stage committed no prefix")?; + ensure!( + prefix.positions == receipt.position_start && row.position < prefix.positions, + "the prefix does not hold one cell per position below the turn" + ); + let digest = root_from_path( + stored, + u64::from(row.layer - stage.layer_start), + u64::from(stage.layer_end - stage.layer_start), + cell_path, + )?; + let root = root_from_path( + // the leaf binds the cell's index alone, not its stream + prefix_leaf( + i32::try_from(row.position)?, + *cell, + &digest, + &parse_hash(leaves)?, + ), + u64::from(row.position), + u64::from(prefix.positions), + prefix_path, + )?; + ensure!( + root == parse_hash(&prefix.root)?, + "the cell is not in the prefix tree" + ); + } + } + Ok(()) +} + +/// The largest error of the picked blocks' partials, recomputed from the +/// committed q and the opened rows, against the partials the node opened. +/// +/// An error is the node's fault: a row or a partial the recomputation +/// needs is missing from what it opened. +pub fn check_blocks( + layout: &AttentionLayout, + head: &OpenedHead, + pick: &BlockPick, + q: &[f32], + rows: &BTreeMap<(u32, u32), ContextRow>, +) -> Result { + recomputed_blocks(layout, head, pick, q, rows).or_node_fault() +} + +fn recomputed_blocks( + layout: &AttentionLayout, + head: &OpenedHead, + pick: &BlockPick, + q: &[f32], + rows: &BTreeMap<(u32, u32), ContextRow>, +) -> Result { + let op = &layout.op; + let len = op.partial_len(); + let mut worst: f64 = 0.0; + for &block in &pick.blocks { + let context = block_positions(&head.context, block) + .map(|position| { + rows.get(&(pick.layer, position)) + .cloned() + .with_context(|| format!("the row at position {position} is not opened")) + }) + .collect::>>()?; + ensure!(!context.is_empty(), "block {block} is past the context"); + let recomputed = block_partial(op, usize::try_from(head.head)?, q, &context)?; + let start = block as usize * len; + let opened = head + .partials + .get(start..start + len) + .context("the partials end before the block")?; + worst = crate::error_bound::worst(worst, partial_error(opened, &recomputed)); + } + Ok(worst) +} + +/// Whether a block's recomputed partial is within the tolerance of the +/// node's. +pub fn block_passed(error: f64) -> bool { + within(error, PARTIAL_TOLERANCE) +} +/// The head's normalized output from its partials. +pub fn combine(op: &AttentionOp, head: usize, partials: &[f32]) -> Result> { + let len = op.partial_len(); + ensure!( + !partials.is_empty() && partials.len().is_multiple_of(len), + "partials of {} values are not whole blocks of {len}", + partials.len() + ); + // `f64::max` below would drop a partial that is not a number + ensure!( + crate::error_bound::all_finite(partials), + "a partial is not a number" + ); + let sink = op + .sinks + .as_ref() + .and_then(|s| s.get(head)) + .map_or(f64::NEG_INFINITY, |&s| f64::from(s)); + let max = partials + .chunks(len) + .map(|p| f64::from(p[0])) + .fold(sink, f64::max); + ensure!(max.is_finite(), "no partial has a finite logit"); + let mut sum = (sink - max).exp(); + let mut out = vec![0.0; op.head_dim_v]; + for p in partials.chunks(len) { + let scale = (f64::from(p[0]) - max).exp(); + sum += scale * f64::from(p[1]); + for (o, &x) in out.iter_mut().zip(&p[2..]) { + *o += scale * f64::from(x); + } + } + ensure!(sum > 0.0, "the partials sum to nothing"); + for o in &mut out { + *o /= sum; + } + Ok(out) +} + +/// How far an opened block partial is from the client's recomputation: +/// the largest of the logit's error (relative to the logit's size, at +/// least 1) and the sum's and values' errors, each relative to the +/// largest of them, which the node rounds to f32. +pub(crate) fn partial_error(opened: &[f32], recomputed: &[f64]) -> f64 { + if opened.len() != recomputed.len() || recomputed.len() < 2 { + return f64::INFINITY; + } + let max_err = (f64::from(opened[0]) - recomputed[0]).abs() / recomputed[0].abs().max(1.0); + let scale = worst( + f64::MIN_POSITIVE, + worst_of(recomputed[1..].iter().map(|x| x.abs())), + ); + let rest = worst_of( + opened[1..] + .iter() + .zip(&recomputed[1..]) + .map(|(&a, &b)| (f64::from(a) - b).abs() / scale), + ); + worst(max_err, rest) +} + +/// How far the combination is from the opened output's head, relative to +/// the larger of their largest values. +pub fn combine_error(combined: &[f64], opened: &[f32]) -> f64 { + if combined.len() != opened.len() { + return f64::INFINITY; + } + let values = combined + .iter() + .map(|x| x.abs()) + .chain(opened.iter().map(|&x| f64::from(x).abs())); + let scale = worst(worst_of(values), f64::MIN_POSITIVE); + let err = worst_of( + combined + .iter() + .zip(opened) + .map(|(&a, &b)| (a - f64::from(b)).abs()), + ); + // an infinite error over an infinite scale is not a number + worst(err / scale, 0.0) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/attention_check/tests.rs b/crates/skippy-receipts/src/attention_check/tests.rs new file mode 100644 index 00000000..104fe43e --- /dev/null +++ b/crates/skippy-receipts/src/attention_check/tests.rs @@ -0,0 +1,364 @@ +use super::*; +use crate::activation_rounding::Profile; +use crate::attention::test_op::{context, exact, op, query, value}; +use crate::attention::{AttentionOp, OutputRotation, head_partials, q_rounding}; +use crate::wire::{MixingKind, TensorOpening}; + +#[test] +fn partials_combine_to_the_exact_attention() { + for (sinks, softcap) in [(None, 0.0), (Some(vec![0.3, -1.0, 2.0, 0.0]), 1.5)] { + let op = AttentionOp { + sinks, + softcap, + ..op() + }; + let rows = context(&op, 150); + let q = query(&op); + for head in 0..op.n_head { + let partials = head_partials(&op, head, &q, &rows).unwrap(); + assert_eq!(partials.len(), 3 * op.partial_len()); + let combined = combine(&op, head, &partials).unwrap(); + let exact: Vec = exact(&op, head, &q, &rows) + .iter() + .map(|&x| x as f32) + .collect(); + assert!(combine_error(&combined, &exact) < 1e-6, "head {head}"); + } + } +} + +#[test] +fn a_dropped_block_is_seen_in_its_partial_or_the_combination() { + let op = op(); + let rows = context(&op, 192); + let q = query(&op); + let honest = head_partials(&op, 1, &q, &rows).unwrap(); + // the node attended to the last two blocks only + let cut: Vec = exact(&op, 1, &q, &rows[64..]) + .iter() + .map(|&x| x as f32) + .collect(); + let honest_out = combine(&op, 1, &honest).unwrap(); + assert!(combine_error(&honest_out, &cut) > COMBINE_TOLERANCE); + // partials that combine to the cut output give the first block no weight + let mut forged = honest.clone(); + forged[1] = 0.0; + forged[2..op.partial_len()].fill(0.0); + assert!(combine_error(&combine(&op, 1, &forged).unwrap(), &cut) < 1e-6); + let recomputed = block_partial(&op, 1, &q, &rows[..64]).unwrap(); + assert!(partial_error(&forged[..op.partial_len()], &recomputed) > 0.5); + assert!(partial_error(&honest[..op.partial_len()], &recomputed) < PARTIAL_TOLERANCE); +} + +fn f32_opening(kind: MixingKind, index: u32, values: &[f32]) -> TensorOpening { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + TensorOpening::new(kind, index, Some((crate::layer_tensors::GGML_F32, &bytes))) +} + +/// Checks the partials of head 1 at the last of 70 positions against an +/// output that `op`'s rotation and then a gate transformed, read as +/// `layout` says. +fn check_transformed( + op: &AttentionOp, + read_as: impl Fn(AttentionLayout) -> AttentionLayout, +) -> bool { + let rows = context(op, 70); + let q = query(op); + let head = 1; + let pick = AttentionPick { + position: 69, + layer: 0, + head_draw: 1, + }; + let opened = AttentionPartials::new(&pick, 1, &head_partials(op, head, &q, &rows).unwrap()); + let gate: Vec = (0..op.n_head * op.head_dim_v) + .map(|i| 0.25 + value(900 + i as u64).abs() / 2.0) + .collect(); + let mut exact = exact(op, head, &q, &rows); + if let Some(rotation) = &op.output_rotation { + rotation.apply(&mut exact).unwrap(); + } + let mut output = vec![0.0; op.n_head * op.head_dim_v]; + for (d, x) in exact.into_iter().enumerate() { + let i = head * op.head_dim_v + d; + output[i] = (x * f64::from(gate[i])) as f32; + } + let leaf = LeafOpening { + position: 69, + residual_in: String::new(), + residual_out: None, + residual_in_path: Vec::new(), + mixing_path: Vec::new(), + residual_out_path: Vec::new(), + mixing: vec![ + f32_opening(MixingKind::Input, 0, &q), + f32_opening(MixingKind::Input, 1, &gate), + f32_opening(MixingKind::Output, 0, &output), + ], + matrices: Vec::new(), + selections: Vec::new(), + }; + let layout = read_as(AttentionLayout { + layer: 0, + op: op.clone(), + q_input: 0, + k_store: 0, + v_store: 1, + output: 0, + output_gate: Some(1), + }); + check_partials(&layout, &pick, &leaf, &opened) + .unwrap() + .passed() +} + +#[test] +fn a_gated_output_is_checked_after_its_gate() { + assert!(check_transformed(&op(), |layout| layout)); + // read as ungated, the committed output is not the attention's + assert!(!check_transformed(&op(), |layout| AttentionLayout { + output_gate: None, + ..layout + })); +} + +#[test] +fn a_rotated_output_is_checked_after_its_rotation() { + let (s, c) = 0.6f32.sin_cos(); + let rotated = AttentionOp { + output_rotation: Some(OutputRotation { + n: 2, + matrix: vec![c, -s, s, c], + }), + ..op() + }; + assert!(check_transformed(&rotated, |layout| layout)); + let unrotated = |layout: AttentionLayout| AttentionLayout { + op: AttentionOp { + output_rotation: None, + ..layout.op.clone() + }, + ..layout + }; + assert!(!check_transformed(&rotated, unrotated)); +} + +#[test] +fn a_rounded_q_is_checked_as_the_kernel_rounds_it() { + let rounded = AttentionOp { + head_dim_k: 32, + q_rounding: Some(q_rounding(8).unwrap()), + ..op() + }; + assert_eq!(rounded.q_rounding, Some(Profile::CpuQ8)); + assert!(check_transformed(&rounded, |layout| layout)); +} + +#[test] +fn values_that_are_not_numbers_fail_the_attention_comparisons() { + let op = op(); + let rows = context(&op, 150); + let q = query(&op); + let honest = head_partials(&op, 1, &q, &rows).unwrap(); + let recomputed = block_partial(&op, 1, &q, &rows[..64]).unwrap(); + let len = op.partial_len(); + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for at in 0..len { + let mut forged = honest.clone(); + forged[at] = bad; + assert!(combine(&op, 1, &forged).is_err(), "value {at} as {bad}"); + assert_eq!(partial_error(&forged[..len], &recomputed), f64::INFINITY); + } + } + // a recomputation that is not a number is no match either + let mut broken = recomputed.clone(); + broken[2] = f64::NAN; + assert_eq!(partial_error(&honest[..len], &broken), f64::INFINITY); + let combined = combine(&op, 1, &honest).unwrap(); + let output: Vec = combined.iter().map(|&x| x as f32).collect(); + assert!(combine_error(&combined, &output) < 1e-6); + for bad in [f32::NAN, f32::INFINITY] { + let mut forged = output.clone(); + forged[1] = bad; + assert_eq!(combine_error(&combined, &forged), f64::INFINITY, "{bad}"); + } + assert_eq!(combine_error(&[f64::NAN, 0.0], &[0.0, 0.0]), f64::INFINITY); +} + +#[test] +fn the_combine_tolerance_grows_with_the_context() { + // a short context keeps the floor + assert_eq!(combine_tolerance(1), COMBINE_TOLERANCE); + assert_eq!(combine_tolerance(400), COMBINE_TOLERANCE); + // the error honest f16 prefill was measured at passes at its context, + // and would fail at a short one + for (context, honest) in [(7_321, 0.0194), (18_876, 0.0285), (29_962, 0.0390)] { + assert!(honest < combine_tolerance(context), "{context}"); + assert!(honest > COMBINE_TOLERANCE * 0.9); + } + assert!(0.0390 > combine_tolerance(1_000)); + // it never grows faster than the square root + assert!(combine_tolerance(32_768) < 0.18); + assert!(combine_tolerance(4_096) < combine_tolerance(16_384)); +} + +mod asked_rows { + use crate::attention::opening::{ + AttentionPick, BlockChallenge, BlockPick, RowOpening, RowProof, RowsOpening, StageRows, + }; + use crate::attention_check::{OpenedHead, verify_answer}; + use crate::node_fault::NodeFault; + use crate::toy_turn::Turn; + + /// One head at position 99 of layer 1, of which block 1 (positions + /// 64..100) is asked, and the rows an honest node opens for it. + fn asked() -> (Turn, BlockChallenge, Vec, RowsOpening) { + let turn = Turn::new(); + let pick = AttentionPick { + position: 99, + layer: 1, + head_draw: 0, + }; + let head = OpenedHead { + pick, + head: 0, + partials: Vec::new(), + context: (0..100).collect(), + combine_error: 0.0, + }; + let blocks = BlockChallenge { + receipt_id: turn.receipt.receipt_id.clone(), + picks: vec![BlockPick { + position: 99, + layer: 1, + blocks: vec![1], + }], + proof: None, + }; + let row = |position| RowOpening { + position, + layer: 1, + stored: Vec::new(), + proof: RowProof::Turn { + rest: String::new(), + path: Vec::new(), + }, + }; + let stage = |stage_index, rows| StageRows { stage_index, rows }; + let rows = RowsOpening { + receipt_id: turn.receipt.receipt_id.clone(), + stages: vec![stage(0, Vec::new()), stage(1, (64..100).map(row).collect())], + }; + (turn, blocks, vec![head], rows) + } + + #[test] + fn the_rows_asked_for_are_accepted() { + let (turn, blocks, heads, rows) = asked(); + verify_answer(&turn.receipt, &blocks, &heads, &rows).unwrap(); + } + + #[test] + fn a_row_left_out_twice_or_unasked_is_the_nodes_fault() { + let changes: [fn(&mut RowsOpening); 7] = [ + |rows| { + rows.stages[1].rows.pop(); + }, + |rows| { + let copy = rows.stages[1].rows[0].clone(); + rows.stages[1].rows.push(copy); + }, + // a row of a block that was not asked + |rows| rows.stages[1].rows[0].position = 3, + |rows| rows.stages[1].rows[0].layer = 0, + // a decoy stage in front, a stage twice, and none + |rows| { + let mut decoy = rows.stages[1].clone(); + decoy.stage_index = 9; + rows.stages.insert(0, decoy); + }, + |rows| rows.stages.push(rows.stages[1].clone()), + |rows| rows.stages.clear(), + ]; + for (i, change) in changes.iter().enumerate() { + let (turn, blocks, heads, mut rows) = asked(); + change(&mut rows); + let error = verify_answer(&turn.receipt, &blocks, &heads, &rows).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "change {i}: {error:#}"); + } + let (turn, blocks, heads, mut rows) = asked(); + rows.receipt_id = "another".into(); + assert!(verify_answer(&turn.receipt, &blocks, &heads, &rows).is_err()); + } +} + +/// The reviewer's forgery: one block whose partial claims a largest logit +/// 100 above the others' carries any output the node likes, since the +/// combination is then that block's values alone. +fn dominant_forgery(op: &AttentionOp, positions: u32, forged_block: usize) -> Vec { + let rows = context(op, positions); + let q = query(op); + let mut partials = head_partials(op, 1, &q, &rows).unwrap(); + let len = op.partial_len(); + let top = partials + .chunks(len) + .map(|p| p[0]) + .fold(f32::NEG_INFINITY, f32::max); + let chosen: Vec = (0..op.head_dim_v).map(|d| value(4000 + d as u64)).collect(); + let forged = &mut partials[forged_block * len..(forged_block + 1) * len]; + forged[0] = top + 100.0; + forged[1] = 1.0; + forged[2..].copy_from_slice(&chosen); + let combined = combine(op, 1, &partials).unwrap(); + assert!( + combine_error(&combined, &chosen) < 1e-6, + "the forgery combines to its choice" + ); + partials +} + +#[test] +fn a_block_that_dominates_the_combination_is_the_one_recomputed() { + // 64 blocks: a uniform draw of two found the forged block 1 in 32 + // times; the draw by the partials' own mass finds it every time + let op = op(); + let partials = dominant_forgery(&op, 64 * BLOCK_POSITIONS as u32, 37); + let masses = block_masses(&partials, 64); + let pick = |seed: u32| AttentionPick { + position: 64 * BLOCK_POSITIONS as u32 - 1, + layer: 0, + head_draw: seed, + }; + let drawn = |masses: &[f64]| { + (0..200u32) + .filter(|&seed| draw_blocks(&seed.to_le_bytes(), &pick(seed), masses).contains(&37)) + .count() + }; + assert_eq!(drawn(&masses), 200); + // the draw that ignored the partials + assert!(drawn(&[1.0; 64]) < 20, "{}", drawn(&[1.0; 64])); + // the second block stays uniform: a block the partials make small, as + // one a node dropped, is still drawn + let seen: BTreeSet = (0..200u32) + .flat_map(|seed| draw_blocks(&seed.to_le_bytes(), &pick(seed), &masses)) + .collect(); + assert!(seen.len() > 40, "{}", seen.len()); +} + +#[test] +fn a_partial_no_block_can_give_is_refused() { + // 130 positions: blocks of 64, 64 and 2 + let op = op(); + let rows = context(&op, 130); + let honest = head_partials(&op, 1, &query(&op), &rows).unwrap(); + let len = op.partial_len(); + check_sums(&honest, len, 130).unwrap(); + for (block, sum) in [(0, 0.0), (0, -3.0), (1, 0.5), (1, 64.5), (2, 2.5)] { + let mut forged = honest.clone(); + forged[block * len + 1] = sum; + assert!( + check_sums(&forged, len, 130).is_err(), + "block {block}, sum {sum}" + ); + } +} diff --git a/crates/skippy-receipts/src/audit.rs b/crates/skippy-receipts/src/audit.rs new file mode 100644 index 00000000..de88e0c2 --- /dev/null +++ b/crates/skippy-receipts/src/audit.rs @@ -0,0 +1,635 @@ +//! Client-side row checks of an opening: weight rows of the claimed GGUF +//! against the opened matmul columns, random rows for most matmuls and +//! every row for a router. The Merkle paths are checked by +//! [`crate::binding`]. +//! +//! The rows come from the VRF output of the opening's hash under the +//! client's key, drawn per weight, so the node cannot know them when it +//! opens and the client cannot pick them. + +use std::collections::BTreeMap; + +use anyhow::{Context, Result}; + +use crate::activation_rounding::Profile; +use crate::draw::DrawStream; +use crate::error_bound::{all_finite, exceeds, worst_of}; +use crate::glue::PlannedMatmul; +use crate::node_fault::{BlameNode, NodeFault, ensure_node, node_fault}; +use crate::rounding_profiles::{BackendFamily, profiles_for}; +use crate::weights::{TensorInfo, WeightFile}; +use crate::wire::{LayerOpening, MatrixOpening}; +use column_check::{CheckedRows, ColumnCheck}; + +mod block_sums; +mod column_check; +#[cfg(test)] +mod metal_tests; +mod near_ties; +pub(crate) mod pairs; +pub(crate) mod rounding_flips; + +/// A column check fails above this relative error (see RECEIPTS.md). +pub(crate) const TOLERANCE: f64 = 1e-3; +pub(crate) const ROWS_PER_MATRIX: usize = 16; +/// A failing column past this error fails its matrix and its role, whatever +/// [`allowed_failing_columns`] allows: the allowance is for honest columns +/// a little past [`TOLERANCE`], not for any value. See RECEIPTS.md, "Fail +/// rule", for the honest values it is set from. +pub(crate) const COLUMN_CAP: f64 = 1e-2; + +/// Failing columns a matrix may have and still pass, for honest outliers +/// that the near-tie repair does not explain. Before the repair, honest +/// backends failed at most 1 in 300 column checks, so an honest matrix of +/// 16 columns had three failures about 1 in 47,000 audits; with it, at +/// most 1 in 8,350 failed, and three failures come about 1 in a billion +/// audits. A majority rule +/// would let a node cheat on half the positions, for example on every +/// decode token of a long prompt. +pub(crate) fn allowed_failing_columns(columns: usize) -> usize { + 2 + columns / 32 +} + +/// [`profiles_for`] (`crate::rounding_profiles`), failing for a pair +/// without profiles. +pub(crate) fn checked_profiles( + family: BackendFamily, + weight_type: u32, +) -> Result<&'static [Profile]> { + profiles_for(family, weight_type).with_context(|| { + format!( + "no rounding profile for {} weights on {family:?}", + crate::ggml_types::type_name(weight_type) + ) + }) +} + +/// Relative error of the checked rows (RECEIPTS.md, "Fail rule"): +/// `||y[R] - y_ref[R]|| / (||y|| · sqrt(|R| / M))`. +pub(crate) fn column_error(rows: &[(usize, &[f64])], x: &[f64], y: &[f32]) -> f64 { + let references: Vec<(usize, f64)> = rows + .iter() + .map(|(m, w)| (*m, w.iter().zip(x).map(|(a, b)| a * b).sum())) + .collect(); + reference_error(&references, y, activation_scale(rows, x)) +} + +/// The norm the checked rows' outputs have for an activation of `x`'s +/// size in no particular direction: `||x|| · ||W[R]||_F / sqrt(K)`. It +/// comes from the client's weights and the activation, which the glue +/// check binds to the layer's computation, so no opened output changes it. +/// Rounding moves an output in proportion to it, where the reference of a +/// row can be small by cancellation. +pub(crate) fn activation_scale(rows: &[(usize, &[f64])], x: &[f64]) -> f64 { + if x.is_empty() { + return 0.0; + } + let weights: f64 = rows.iter().flat_map(|(_, w)| w.iter()).map(|w| w * w).sum(); + let activation: f64 = x.iter().map(|v| v * v).sum(); + (weights * activation / x.len() as f64).sqrt() +} + +/// [`column_error`] of the reference outputs of the checked rows: +/// `||y[R] - y_ref[R]|| / max(||y_ref[R]||, floor)`, with `floor` the +/// rows' [`activation_scale`]. +/// +/// Every term is over the checked rows alone, and the scale is the +/// client's own. A scale over every opened output would let a node hide +/// any error behind one huge value in a row the client did not draw, which +/// a later op can cancel (a gate of -1e6 silences its neuron). +fn reference_error(references: &[(usize, f64)], y: &[f32], floor: f64) -> f64 { + let diff2: f64 = references + .iter() + .map(|&(m, reference)| (f64::from(y[m]) - reference).powi(2)) + .sum(); + let scale = references + .iter() + .map(|&(_, reference)| reference * reference) + .sum::() + .sqrt() + .max(floor); + if scale == 0.0 { + return if diff2 == 0.0 { 0.0 } else { f64::INFINITY }; + } + diff2.sqrt() / scale +} + +#[derive(Clone, Debug)] +pub struct MatrixVerdict { + pub weight: String, + pub weight_type: String, + /// A router: every row was checked. + pub router: bool, + /// No column may fail: a router of float weights ([`exact_router`]). + pub exact: bool, + /// Columns checked: one per position, or one per expert used. + pub tokens: usize, + pub failing_tokens: usize, + /// Failing columns past [`COLUMN_CAP`], each of which fails the matrix. + pub past_cap: usize, + /// Columns that pass only once a repair rounds near-ties of their + /// activation the other way ([`near_ties`]). + pub repaired_tokens: usize, + pub max_error: f64, + pub best_profile: &'static str, + pub pass: bool, +} + +#[derive(Clone, Debug)] +pub struct AuditReport { + pub layer: u32, + pub tokens: usize, + pub matrices: Vec, + pub pass: bool, +} + +/// One opened matmul column split into the slices one weight row meets: a +/// `mul_mat_id` has one per expert used, a batched matmul one per batch. +struct MatmulSlices { + /// Values per weight row (K) and rows per weight matrix (M). + k: usize, + m: usize, + /// Per output slice: the first weight row and the input slice. + slices: Vec<(u64, usize)>, +} + +/// Checks that an opened matmul of `x` input and `y` output values fits +/// the claimed weight `tensor`: whole rows and columns of it, one slice per +/// expert named, and every expert one the weight holds. +/// +/// An error is the node's fault: the weight's shape comes from the claimed +/// GGUF's header. +pub(crate) fn check_matmul_shape( + tensor: &TensorInfo, + m: &MatrixOpening, + x: usize, + y: usize, +) -> Result<()> { + matmul_slices(tensor, m, x, y).map(|_| ()) +} + +fn matmul_slices( + tensor: &TensorInfo, + m: &MatrixOpening, + x: usize, + y: usize, +) -> Result { + let k = usize::try_from(tensor.row_len())?; + let rows = usize::try_from(tensor.rows())?; + let matrices = tensor.dims.get(2).copied().unwrap_or(1); + let shape = || { + NodeFault::error(format!( + "{}: opened input of {x} and output of {y} values do not fit the claimed weight {:?}", + m.weight, tensor.dims + )) + }; + // an empty column would pass every comparison + if k == 0 || rows == 0 || x == 0 || y == 0 || !x.is_multiple_of(k) || !y.is_multiple_of(rows) { + return Err(shape()); + } + let (groups_in, groups_out) = (x / k, y / rows); + let slices = match &m.experts { + Some(experts) => { + if experts.len() != groups_out || (groups_in != 1 && groups_in != groups_out) { + return Err(shape()); + } + experts + .iter() + .enumerate() + .map(|(g, &e)| { + let Some(e) = u64::try_from(e).ok().filter(|&e| e < matrices) else { + node_fault!("{}: expert {e} outside {matrices} experts", m.weight); + }; + Ok((e * rows as u64, if groups_in == 1 { 0 } else { g })) + }) + .collect::>()? + } + None => { + if groups_in != groups_out { + return Err(shape()); + } + match matrices { + 1 => (0..groups_out).map(|g| (0, g)).collect(), + n if n == groups_out as u64 => (0..groups_out) + .map(|g| (g as u64 * rows as u64, g)) + .collect(), + _ => return Err(shape()), + } + } + }; + Ok(MatmulSlices { k, m: rows, slices }) +} + +/// What the row check knows of a layer's matmuls. +#[derive(Clone, Copy, Debug)] +pub enum Routers<'a> { + /// The layer as the auditor's own evaluation has it: which weight each + /// matmul reads, and which are routers. + Planned(&'a MatmulPlan), + /// The auditor could not evaluate the layer. No matmul is taken for a + /// router, so each is checked on a sample of its rows and none on all + /// of them: the opening may not decide what the client reads. A column + /// that fails is still a failure; a layer that passes this way was not + /// held to the weights its matmuls read. + Unknown, +} + +impl Routers<'_> { + /// Whether the opened matmul `m` is a router. With a plan, an opening + /// that names another weight for the index, or an index the layer does + /// not have, is the node's fault. The router flag the node sent is + /// never read. + fn is_router(self, position: u32, m: &MatrixOpening) -> Result { + let Self::Planned(plan) = self else { + return Ok(false); + }; + let Some(planned) = plan.get(&m.index) else { + node_fault!( + "position {position}: the layer has no matmul {} ({})", + m.index, + m.weight + ); + }; + ensure_node!( + planned.weight == m.weight, + "position {position}: matmul {} reads {}, opened as {}", + m.index, + planned.weight, + m.weight + ); + Ok(planned.router) + } + + /// Whether a layer with these matmuls may open none. + fn allows_none(self) -> bool { + match self { + Self::Planned(plan) => plan.is_empty(), + Self::Unknown => true, + } + } +} + +/// The claimed weight an opened matmul names. A name the GGUF does not +/// have is the node's fault. +fn named_weight<'a>(weights: &'a WeightFile, m: &MatrixOpening) -> Result<&'a TensorInfo> { + let Some(tensor) = weights.tensors.get(&m.weight) else { + node_fault!( + "matmul {} names {:?}, a tensor the claimed GGUF does not have", + m.index, + m.weight + ); + }; + Ok(tensor) +} + +/// Fetches every row the checks of `opening` read in one round, so a +/// sparse copy of the claimed GGUF makes its requests at once and not one +/// per row. +fn prefetch_rows( + weights: &WeightFile, + cache: &mut RowCache, + opening: &LayerOpening, + routers: Routers<'_>, + seed: &[u8], +) -> Result<()> { + let mut ranges = Vec::new(); + let leaves = opening.leaves.iter(); + for (position, m) in leaves.flat_map(|leaf| leaf.matrices.iter().map(|m| (leaf.position, m))) { + let router = routers.is_router(position, m)?; + let tensor = named_weight(weights, m)?; + let (inputs, outputs) = m.value_counts().or_node_fault()?; + let shape = matmul_slices(tensor, m, inputs, outputs)?; + let picked = cache.picked(&m.weight, shape.m, router, seed); + for g in cache.checked_slices(m, position, shape.slices.len()) { + let (base, _) = shape.slices[g]; + for &r in &picked { + ranges.push(weights.row_range(&m.weight, base + r as u64)?); + } + } + } + weights.prefetch(&ranges) +} + +/// Weight rows already read, by tensor and row. +#[derive(Default)] +struct RowCache { + rows: BTreeMap<(String, u64), Vec>, + /// The same rows as sub-blocks, for the profiles with block sums. + blocks: BTreeMap<(String, u64), Vec>, + /// Row indices checked per weight; every row for a router. + picked: BTreeMap>, + /// The (position, expert) pairs whose expert matmuls are checked, for + /// a MoE layer. + pairs: Option>, +} + +impl RowCache { + /// The output slices of `m` at `position` to check: every one, but for + /// an expert matmul only the slices of the picked pairs. + fn checked_slices(&self, m: &MatrixOpening, position: u32, slices: usize) -> Vec { + match (&m.experts, &self.pairs) { + (Some(experts), Some(pairs)) => (0..slices) + .filter(|&g| { + experts + .get(g) + .is_some_and(|&e| pairs.contains(&(position, e))) + }) + .collect(), + _ => (0..slices).collect(), + } + } + + fn picked(&mut self, weight: &str, m: usize, all: bool, seed: &[u8]) -> Vec { + self.picked + .entry(weight.to_owned()) + .or_insert_with(|| { + if all || m <= ROWS_PER_MATRIX { + return (0..m).collect(); + } + let mut stream = DrawStream::new(seed, &format!("rows/{weight}")); + let mut picked = std::collections::BTreeSet::new(); + while picked.len() < ROWS_PER_MATRIX { + picked.insert(stream.below(m as u64) as usize); + } + picked.into_iter().collect() + }) + .clone() + } + + fn load_blocks(&mut self, weights: &WeightFile, weight: &str, row: u64) -> Result<()> { + if let std::collections::btree_map::Entry::Vacant(entry) = + self.blocks.entry((weight.to_owned(), row)) + { + entry.insert(weights.min_blocks(weight, row)?); + } + Ok(()) + } + + fn load(&mut self, weights: &WeightFile, weight: &str, row: u64) -> Result<()> { + if let std::collections::btree_map::Entry::Vacant(entry) = + self.rows.entry((weight.to_owned(), row)) + { + entry.insert(weights.row(weight, row)?); + } + Ok(()) + } +} + +/// Column checks of every slice of one opened matmul column, each with +/// its best profile. +fn matmul_errors( + weights: &WeightFile, + cache: &mut RowCache, + (position, m, router): (u32, &MatrixOpening, bool), + seed: &[u8], + family: BackendFamily, +) -> Result> { + let x = m.input_values().or_node_fault()?; + let y = m.output_values().or_node_fault()?; + ensure_node!( + all_finite(&x) && all_finite(&y), + "position {position}: {} is opened with a value that is not a number", + m.weight + ); + let tensor = named_weight(weights, m)?; + let profiles = checked_profiles(family, tensor.ggml_type)?; + let shape = matmul_slices(tensor, m, x.len(), y.len())?; + let picked = cache.picked(&m.weight, shape.m, router, seed); + let sums = profiles.iter().any(|p| p.block_sums().is_some()); + let mut checks = Vec::with_capacity(shape.slices.len()); + for g in cache.checked_slices(m, position, shape.slices.len()) { + let (base, input) = shape.slices[g]; + for &r in &picked { + cache.load(weights, &m.weight, base + r as u64)?; + if sums { + cache.load_blocks(weights, &m.weight, base + r as u64)?; + } + } + let key = |r: usize| (m.weight.clone(), base + r as u64); + let rows = CheckedRows { + rows: picked + .iter() + .map(|&r| (r, cache.rows[&key(r)].as_slice())) + .collect(), + blocks: match sums { + true => picked + .iter() + .map(|&r| cache.blocks[&key(r)].as_slice()) + .collect(), + false => Vec::new(), + }, + }; + let xs = &x[input * shape.k..(input + 1) * shape.k]; + let ys = &y[g * shape.m..(g + 1) * shape.m]; + let best = profiles + .iter() + .map(|&p| rows.check(p, xs, ys)) + .min_by(|a, b| a.error.total_cmp(&b.error)) + .expect("profiles"); + checks.push(best); + } + Ok(checks) +} + +/// A layer's weight matmuls by index, as the auditor's own graph has them +/// ([`crate::glue::GlueReport::matmuls`]). +pub(crate) type MatmulPlan = BTreeMap; + +/// Row checks of every opened matrix against the claimed weights, on rows +/// drawn from `seed`, with the profiles of `backend`, the backend the +/// receipt names for the layer's stage. +/// +/// `routers` is the layer as the auditor built it, when it could: which +/// weight each matmul reads and which are routers. The opening's own +/// router flags are not read, since a router costs a read of every row. +/// Each matmul may be opened once per position, so a column counts once +/// toward [`allowed_failing_columns`]. +/// +/// An error that blames the node ([`crate::node_fault::NodeFault`]) is a +/// defect of the opening. Any other error is the auditor's: it could not +/// read the claimed weights. +pub fn check_rows( + weights: &WeightFile, + opening: &LayerOpening, + routers: Routers<'_>, + seed: &[u8], + backend: &str, +) -> Result { + let family = BackendFamily::checked(backend)?; + for leaf in &opening.leaves { + let mut seen = std::collections::BTreeSet::new(); + if let Some(twice) = leaf.matrices.iter().find(|m| !seen.insert(m.index)) { + node_fault!( + "position {}: matmul {} ({}) is opened more than once", + leaf.position, + twice.index, + twice.weight + ); + } + } + // weight name -> per-column (error, profile), and whether it is a router + let mut per_matrix: BTreeMap)> = BTreeMap::new(); + let mut cache = RowCache { + pairs: pairs::picked_pairs(opening, seed), + ..RowCache::default() + }; + prefetch_rows(weights, &mut cache, opening, routers, seed)?; + for leaf in &opening.leaves { + for m in &leaf.matrices { + let router = routers.is_router(leaf.position, m)?; + let column = (leaf.position, m, router); + let checks = matmul_errors(weights, &mut cache, column, seed, family)?; + let entry = per_matrix.entry(m.weight.clone()).or_default(); + entry.0 |= router; + entry.1.extend(checks); + } + } + let matrices: Vec = per_matrix + .into_iter() + .map(|(weight, (router, checks))| verdict(weights, weight, router, &checks)) + .collect::>()?; + ensure_node!( + !matrices.is_empty() || routers.allows_none(), + "the opening has no matrices to check" + ); + let pass = matrices.iter().all(|m| m.pass); + Ok(AuditReport { + layer: opening.layer, + tokens: opening.leaves.len(), + matrices, + pass, + }) +} + +fn verdict( + weights: &WeightFile, + weight: String, + router: bool, + checks: &[ColumnCheck], +) -> Result { + // an error that is not a number fails its column + let failing = checks + .iter() + .filter(|c| exceeds(c.error, TOLERANCE)) + .count(); + let repaired = checks.iter().filter(|c| c.flips > 0).count(); + let max_error = worst_of(checks.iter().map(|c| c.error)); + let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); + for c in checks { + *counts.entry(c.profile).or_default() += 1; + } + let best_profile = counts + .into_iter() + .max_by_key(|(_, n)| *n) + .map(|(p, _)| p) + .unwrap_or("raw"); + let past_cap = checks + .iter() + .filter(|c| exceeds(c.error, COLUMN_CAP)) + .count(); + let ggml_type = weights.tensor(&weight)?.ggml_type; + let exact = exact_router(router, ggml_type); + Ok(MatrixVerdict { + router, + exact, + tokens: checks.len(), + failing_tokens: failing, + past_cap, + repaired_tokens: repaired, + max_error, + best_profile, + pass: passes(failing, past_cap, checks.len(), exact), + weight_type: crate::ggml_types::type_name(ggml_type), + weight, + }) +} + +/// One weight role (`attn_q.weight`, `ffn_down_exps.weight`, ...) across +/// every opened layer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RoleVerdict { + pub role: String, + pub layers: Vec, + pub router: bool, + /// No column may fail ([`exact_router`]). + pub exact: bool, + pub tokens: usize, + pub failing_tokens: usize, + /// Failing columns past [`COLUMN_CAP`]. + pub past_cap: usize, + pub pass: bool, +} + +/// The fail rule over a whole challenge. A challenge opens a few positions +/// in each of several layers, too few per matrix for +/// [`allowed_failing_columns`] to bite: with four columns, two failures +/// would pass. So each weight role is judged on its columns in every opened +/// layer together, which gives the rule as many columns as one layer of 16 +/// positions had. +pub fn pool_roles(reports: &[AuditReport]) -> Vec { + let mut roles: BTreeMap = BTreeMap::new(); + for report in reports { + for m in &report.matrices { + let role = weight_role(&m.weight).to_owned(); + let entry = roles.entry(role.clone()).or_insert_with(|| RoleVerdict { + role, + layers: Vec::new(), + router: false, + exact: m.exact, + tokens: 0, + failing_tokens: 0, + past_cap: 0, + pass: true, + }); + entry.layers.push(report.layer); + entry.router |= m.router; + entry.exact &= m.exact; + entry.tokens += m.tokens; + entry.failing_tokens += m.failing_tokens; + entry.past_cap += m.past_cap; + } + } + roles + .into_values() + .map(|mut role| { + role.pass = passes(role.failing_tokens, role.past_cap, role.tokens, role.exact); + role + }) + .collect() +} + +/// The fail rule of a matrix or a role: no failing column past +/// [`COLUMN_CAP`], and at most [`allowed_failing_columns`] of its +/// `columns` failing; none at all when `exact`. +fn passes(failing: usize, past_cap: usize, columns: usize, exact: bool) -> bool { + let allowed = if exact { + 0 + } else { + allowed_failing_columns(columns) + }; + past_cap == 0 && failing <= allowed +} + +/// Whether no column of a matmul may fail: a router of float weights. A +/// router steers the selection, so every row of it is checked; with f32, +/// f16 or bf16 weights an honest backend computes it with no failing +/// column. A quantized router (stock `llama-quantize` keeps `ffn_gate_inp` +/// in f32, but other tools need not) rounds as other quantized weights do +/// and gets their allowance, or an honest node would fail about 1 in 400 +/// audits. +fn exact_router(router: bool, ggml_type: u32) -> bool { + use crate::ggml_types::{GGML_BF16, GGML_F16, GGML_F32}; + router && matches!(ggml_type, GGML_F32 | GGML_F16 | GGML_BF16) +} + +/// A weight's name without its `blk.N.` prefix. +fn weight_role(weight: &str) -> &str { + weight + .strip_prefix("blk.") + .and_then(|rest| rest.split_once('.')) + .filter(|(layer, _)| layer.bytes().all(|b| b.is_ascii_digit())) + .map_or(weight, |(_, role)| role) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/audit/block_sums.rs b/crates/skippy-receipts/src/audit/block_sums.rs new file mode 100644 index 00000000..9c536377 --- /dev/null +++ b/crates/skippy-receipts/src/audit/block_sums.rs @@ -0,0 +1,135 @@ +//! CUDA MMQ for weights with a minimum per 32 values (Q4_K, Q5_K). +//! +//! The kernel does not subtract the minimum from each weight. Per 32 +//! values it computes `A · d8 · Σ q·q8 + M · S`, with `q` the weight's +//! quants, `q8` and `d8` the activation quantized as `quantize_mmq_q8_1` +//! does, `S` the block sum that function stores as f16, and `A = d·scale` +//! and `M = −dmin·min`. The MMA kernels (Turing and later) round `A` and +//! `M` to f16 (`load_tiles_q4_K`, `load_tiles_q5_K`); the dp4a kernels keep +//! them exact. +//! +//! `S` is the block's f32 scale times the sum of its quants +//! (`d * float(sum_q)`), not the scale as f16 that the products use, so an +//! activation profile alone does not reproduce these matmuls. Before +//! llama.cpp #31247 it was the sum of the unquantized activation; a +//! receipt names its runtime, and a verifier of another one does not audit +//! it, so only the current rule is kept. + +use half::f16; + +use crate::dequant::MinBlock; + +/// The kernel's output for one weight row, with the activation `x` and its +/// MMQ quantization `xq`. +pub(super) fn reference(blocks: &[MinBlock], x: &[f32], xq: &[f64], rounded: bool) -> f64 { + let round = |v: f64| kernel_scale(v, rounded); + blocks + .iter() + .zip(x.chunks(32).zip(xq.chunks(32))) + .map(|(block, (x, xq))| { + let dot: f64 = block + .quants + .iter() + .zip(xq) + .map(|(&q, &a)| f64::from(q) * a) + .sum(); + round(block.scale) * dot - round(block.min) * stored_sum(x) + }) + .sum() +} + +/// The sum of one block of the activation as `quantize_mmq_q8_1` stores +/// it: the block's scale times the sum of its quants, computed in f32 and +/// kept as f16. +fn stored_sum(x: &[f32]) -> f64 { + let amax = x.iter().fold(0.0f32, |m, v| m.max(v.abs())); + if amax == 0.0 { + return 0.0; + } + let d_inv = 127.0 / amax; + let quants: i32 = x.iter().map(|&v| (v * d_inv).round() as i32).sum(); + let d = 1.0 / d_inv; + f16::from_f32(d * quants as f32).to_f64() +} + +/// The weight that value `i` of the quantized activation meets: its +/// block's scale times its quant, less the block's minimum, because the +/// stored sum moves with each quant of the activation too. +pub(super) fn activation_weight(blocks: &[MinBlock], i: usize, rounded: bool) -> f64 { + let block = &blocks[i / 32]; + kernel_scale(block.scale, rounded) * f64::from(block.quants[i % 32]) + - kernel_scale(block.min, rounded) +} + +/// A weight scale or minimum as the kernel holds it. +fn kernel_scale(v: f64, rounded: bool) -> f64 { + if rounded { + f16::from_f64(v).to_f64() + } else { + v + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::activation_rounding::Profile; + + /// The activation quantization of the MMQ kernels with block sums. + fn quantized(x: &[f32]) -> Vec { + Profile::Q8MulHalfSums.apply(x) + } + + #[test] + fn the_minimum_meets_the_stored_sum_of_the_quantized_activation() { + let block = MinBlock { + scale: 0.5, + min: 0.25, + quants: [2; 32], + }; + // one large value sets the scale; the others round to 38 of 127 + let mut x = [0.3f32; 32]; + x[0] = 1.0; + let xq = quantized(&x); + let d_inv = 127.0f32; + let quants = 127 + 31 * (0.3f32 * d_inv).round() as i32; + let sum = f64::from(f16::from_f32((1.0 / d_inv) * quants as f32).to_f32()); + assert_eq!(stored_sum(&x), sum); + let expected = 0.5 * 2.0 * xq.iter().sum::() - 0.25 * sum; + let got = reference(std::slice::from_ref(&block), &x, &xq, true); + assert!((got - expected).abs() < 1e-12, "{got} {expected}"); + // it is not the sum of the unquantized activation + let unquantized = f64::from(f16::from_f32(x.iter().sum::()).to_f32()); + assert_ne!(sum, unquantized); + // a block of zeros has a zero sum, not a quotient by zero + assert_eq!(stored_sum(&[0.0; 32]), 0.0); + } + + #[test] + fn a_quant_of_the_activation_meets_the_scale_and_the_minimum() { + let block = MinBlock { + scale: 0.5, + min: 0.25, + quants: [2; 32], + }; + let blocks = std::slice::from_ref(&block); + assert_eq!(activation_weight(blocks, 3, true), 0.5 * 2.0 - 0.25); + } + + #[test] + fn mma_kernels_round_the_scales_to_f16() { + let block = MinBlock { + scale: 1.0 + 1.0 / 4096.0, + min: 0.0, + quants: [1; 32], + }; + let x = [1.0f32; 32]; + let xq = quantized(&x); + let unscaled: f64 = xq.iter().sum(); + assert_eq!( + reference(std::slice::from_ref(&block), &x, &xq, true), + unscaled + ); + assert!(reference(std::slice::from_ref(&block), &x, &xq, false) > unscaled); + } +} diff --git a/crates/skippy-receipts/src/audit/column_check.rs b/crates/skippy-receipts/src/audit/column_check.rs new file mode 100644 index 00000000..58b14431 --- /dev/null +++ b/crates/skippy-receipts/src/audit/column_check.rs @@ -0,0 +1,139 @@ +//! One column check: the opened output of a matmul at one position +//! against the claimed weight rows the client drew, under one rounding +//! profile, repaired when an activation near-tie fails it +//! ([`super::near_ties`]). + +use super::rounding_flips::{self, Flip}; +use super::{TOLERANCE, activation_scale, block_sums, near_ties, reference_error}; +use crate::activation_rounding::Profile; +use crate::dequant::MinBlock; + +/// One column check: its error, the profile that gave it, and the +/// near-ties a repair rounded the other way ([`near_ties`]). +#[derive(Clone, Copy, Debug)] +pub(super) struct ColumnCheck { + pub(super) error: f64, + pub(super) profile: &'static str, + pub(super) flips: usize, +} + +/// The checked weight rows of one output slice, as each profile meets the +/// activation. +pub(super) struct CheckedRows<'a> { + /// Per checked row: its index and its dequantized weights. + pub(super) rows: Vec<(usize, &'a [f64])>, + /// The same rows as sub-blocks, for the profiles with block sums. + pub(super) blocks: Vec<&'a [MinBlock]>, +} + +impl CheckedRows<'_> { + /// The reference outputs of the checked rows for the activation `x`, + /// which `p` rounds to `xq`. + fn references(&self, p: Profile, x: &[f32], xq: &[f64]) -> Vec<(usize, f64)> { + match p.block_sums() { + Some(rounded) => self + .rows + .iter() + .zip(&self.blocks) + .map(|(&(r, _), blocks)| (r, block_sums::reference(blocks, x, xq, rounded))) + .collect(), + None => self + .rows + .iter() + .map(|&(r, w)| (r, w.iter().zip(xq).map(|(&w, a)| p.weight(w) * a).sum())) + .collect(), + } + } + + /// The weight that value `i` of the rounded activation meets in the + /// `k`-th checked row. + fn weight(&self, p: Profile, k: usize, i: usize) -> f64 { + match p.block_sums() { + Some(rounded) => block_sums::activation_weight(self.blocks[k], i, rounded), + None => p.weight(self.rows[k].1[i]), + } + } + + /// The column check of `x` against the opened output `y` under `p`, + /// repaired when a near-tie fails it. + pub(super) fn check(&self, p: Profile, x: &[f32], y: &[f32]) -> ColumnCheck { + let xq = p.apply(x); + let references = self.references(p, x, &xq); + let floor = activation_scale(&self.rows, &xq); + let error = reference_error(&references, y, floor); + let unrepaired = ColumnCheck { + error, + profile: p.name(), + flips: 0, + }; + if error <= TOLERANCE { + return unrepaired; + } + let flips = rounding_flips::flips(p, x, &xq); + let effect = |k: usize, flip: &Flip| { + flip.changes + .iter() + .map(|&(i, change)| self.weight(p, k, i) * change) + .sum() + }; + near_ties::repair(&references, y, floor, &flips, effect).map_or(unrepaired, |repair| { + ColumnCheck { + error: repair.error, + flips: repair.flips, + ..unrepaired + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_column_a_near_tie_failed_is_repaired() { + // d = 0.01: 0.255 lies on the boundary between steps 25 and 26 + let mut x = vec![0.05f32; 32]; + x[0] = 1.27; + x[5] = 0.255; + let p = Profile::Q8DivHalf; + let xq = p.apply(&x); + let tie = rounding_flips::flips(p, &x, &xq) + .into_iter() + .find(|f| f.changes.iter().any(|&(i, _)| i == 5)) + .expect("value 5 is a near-tie"); + let mut node = xq.clone(); + for &(i, change) in &tie.changes { + node[i] += change; + } + let w: Vec> = (0..4) + .map(|r| { + (0..32) + .map(|i| f64::from((r * 7 + i * 3) % 11) * 0.1 - 0.5) + .collect() + }) + .collect(); + let y: Vec = w + .iter() + .map(|row| row.iter().zip(&node).map(|(a, b)| a * b).sum::() as f32) + .collect(); + let rows = CheckedRows { + rows: w + .iter() + .enumerate() + .map(|(r, row)| (r, row.as_slice())) + .collect(), + blocks: Vec::new(), + }; + assert!(reference_error(&rows.references(p, &x, &xq), &y, 0.0) > TOLERANCE); + let check = rows.check(p, &x, &y); + assert_eq!(check.flips, 1, "{check:?}"); + assert!(check.error <= near_ties::REPAIRED_TOLERANCE, "{check:?}"); + + // other weights are not repaired + let other: Vec = y.iter().map(|v| v * 1.05).collect(); + let check = rows.check(p, &x, &other); + assert_eq!(check.flips, 0); + assert!(check.error > TOLERANCE); + } +} diff --git a/crates/skippy-receipts/src/audit/metal_tests.rs b/crates/skippy-receipts/src/audit/metal_tests.rs new file mode 100644 index 00000000..54b0e4a4 --- /dev/null +++ b/crates/skippy-receipts/src/audit/metal_tests.rs @@ -0,0 +1,112 @@ +//! Hardware-captured values, with no Metal dependency in the offline tests. +//! See evals/receipts-metal/README.md for provenance and the remaining gates. +use super::column_check::CheckedRows; +use crate::activation_rounding::Profile; +use crate::rounding_profiles::{BackendFamily, profiles_for}; + +const WIDTH: usize = 256; +const ROWS: usize = 16; +const POSITIONS: usize = 17; + +fn capture(name: &str, saved: &[u8]) -> Vec { + // An explicit hardware run supplies fresh captures; default tests are offline. + let fresh = std::env::var_os("SKIPPY_METAL_CAPTURE_DIR").map(|dir| { + std::fs::read(std::path::PathBuf::from(dir).join(name)).expect("read fresh Metal capture") + }); + let bytes = fresh.as_deref().unwrap_or(saved); + assert_eq!( + bytes.len(), + 4 * (WIDTH * ROWS + WIDTH * POSITIONS + ROWS * (1 + POSITIONS)) + ); + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|v| f32::from_le_bytes(*v)) + .collect() +} + +#[test] +fn captured_metal_decode_and_both_prefill_paths_match() { + for (name, bytes, profile) in [ + ( + "tensor.f32le", + include_bytes!("../../tests/fixtures/metal/tensor.f32le").as_slice(), + Profile::MetalTensor, + ), + ( + "legacy.f32le", + include_bytes!("../../tests/fixtures/metal/legacy.f32le").as_slice(), + Profile::F16Weights, + ), + ] { + let values = capture(name, bytes); + assert!(values.iter().all(|v| v.is_finite())); + let (weights, rest) = values.split_at(WIDTH * ROWS); + let (x, rest) = rest.split_at(WIDTH * POSITIONS); + let (decode, prefill) = rest.split_at(ROWS); + let w: Vec = weights.iter().map(|&v| f64::from(v)).collect(); + let rows = CheckedRows { + rows: w + .as_chunks::() + .0 + .iter() + .enumerate() + .map(|(r, w)| (r, w.as_slice())) + .collect(), + blocks: Vec::new(), + }; + assert!(rows.check(Profile::Raw, &x[..WIDTH], decode).error < 2e-6); + let mut worst = 0.0f64; + let mut raw_worst = 0.0f64; + for (x, y) in x + .as_chunks::() + .0 + .iter() + .zip(prefill.as_chunks::().0) + { + let check = rows.check(profile, x, y); + assert!(check.error < 2e-6, "{name}: {check:?}"); + assert_eq!(check.flips, 0, "{name}: no repair should be necessary"); + worst = worst.max(check.error); + raw_worst = raw_worst.max(rows.check(Profile::Raw, x, y).error); + // A wrong output must still fail the unchanged production tolerance. + let other: Vec = y.iter().map(|v| v * 1.05).collect(); + assert!(rows.check(profile, x, &other).error > super::TOLERANCE); + } + assert!( + raw_worst > 1e-4, + "fixture must distinguish this path from raw: {raw_worst}" + ); + eprintln!("{name}: matched={worst:e}, raw={raw_worst:e}"); + } +} + +#[test] +fn tensor_fraction_is_truncated_not_rounded_or_reexponented() { + let x = [1.0009, -1.0009, 100_000.0, -0.0, f32::from_bits(0x1fff)]; + let rounded = Profile::MetalTensor.apply(&x); + assert_eq!(&rounded[..2], &[1.0, -1.0]); + assert_eq!(rounded[2], 99_968.0); + assert_eq!(rounded[3].to_bits(), (-0.0f64).to_bits()); + assert_eq!(rounded[4], 0.0); + assert_ne!(rounded[0], Profile::F16.apply(&x)[0]); + let special = Profile::MetalTensor.apply(&[f32::from_bits(0x7f80_0001), f32::INFINITY]); + assert!(special[0].is_nan()); + assert_eq!(special[1], f64::INFINITY); +} + +#[test] +fn matrix_candidates_do_not_enable_unqualified_metal_receipts() { + for backend in ["MTL0", "MTL1", "Metal"] { + assert_eq!(BackendFamily::of(backend), None); + } + for family in [BackendFamily::Cpu, BackendFamily::Cuda] { + for weight_type in 0..=40 { + if let Some(profiles) = profiles_for(family, weight_type) { + assert!(!profiles.contains(&Profile::MetalTensor)); + assert!(!profiles.contains(&Profile::F16Weights)); + } + } + } +} diff --git a/crates/skippy-receipts/src/audit/near_ties.rs b/crates/skippy-receipts/src/audit/near_ties.rs new file mode 100644 index 00000000..c250f039 --- /dev/null +++ b/crates/skippy-receipts/src/audit/near_ties.rs @@ -0,0 +1,171 @@ +//! Repair of a column check that an activation near-tie failed. +//! +//! A backend rounds the activation to its profile's grid before the +//! weights meet it. When the value it rounded differs from the opened one +//! by a few ulps (a fused kernel computes it again, or divides with a fast +//! reciprocal), a value that lies on a rounding boundary rounds the other +//! way, and the output moves by one step of that value times its weight +//! column. That is far above [`super::TOLERANCE`] for some columns, though +//! the node computed honestly, and it was the main source of honest column +//! failures (RECEIPTS.md, "Fail rule"). +//! +//! The repair rounds at most two of the activation's near-ties +//! ([`rounding_flips`]) the other way and keeps the result only when it +//! explains the difference on every checked row, within +//! [`REPAIRED_TOLERANCE`]. That gives the node no freedom: a flip is a fixed +//! change of the reference, known only once the client has drawn the rows, +//! and the values that can flip lie in the opened activation, which the +//! glue check binds to the layer's computation. + +use super::rounding_flips::{Flip, PAIRED_FLIPS}; +use super::{TOLERANCE, reference_error}; + +/// The error a repaired column must reach: well under the tolerance, so a +/// repair explains the difference and does not merely bring it under the +/// bar. +pub(crate) const REPAIRED_TOLERANCE: f64 = TOLERANCE / 4.0; + +/// The best repair of a column: its error, and how many near-ties it +/// rounded the other way. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Repair { + pub error: f64, + pub flips: usize, +} + +/// Repairs a column whose checked rows have the reference outputs +/// `references`, against the opened output `y`, with the scale floor of +/// [`super::reference_error`]. `effect(k, flip)` is the +/// change `flip` makes to the reference of the `k`-th checked row. Returns +/// `None` when no repair of at most two flips reaches +/// [`REPAIRED_TOLERANCE`]. +pub fn repair( + references: &[(usize, f64)], + y: &[f32], + floor: f64, + flips: &[Flip], + effect: impl Fn(usize, &Flip) -> f64, +) -> Option { + let effects: Vec> = flips + .iter() + .map(|flip| (0..references.len()).map(|k| effect(k, flip)).collect()) + .collect(); + let error = |taken: &[usize]| { + let moved: Vec<(usize, f64)> = references + .iter() + .enumerate() + .map(|(k, &(row, reference))| { + ( + row, + reference + taken.iter().map(|&f| effects[f][k]).sum::(), + ) + }) + .collect(); + reference_error(&moved, y, floor) + }; + let mut best: Option = None; + let mut consider = |taken: &[usize]| { + let e = error(taken); + if best.is_none_or(|b| e < b.error) { + best = Some(Repair { + error: e, + flips: taken.len(), + }); + } + }; + for a in 0..flips.len() { + consider(&[a]); + if flips.len() <= PAIRED_FLIPS { + for b in a + 1..flips.len() { + consider(&[a, b]); + } + } + } + best.filter(|b| b.error <= REPAIRED_TOLERANCE) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn flip(i: usize, change: f64) -> Flip { + Flip { + changes: vec![(i, change)], + } + } + + /// A 4-row matrix, the client's activation, and the node's output when + /// value `i` of the activation rounded by `step` the other way. + fn column(tied: Option<(usize, f64)>) -> (Vec>, Vec, Vec) { + let w: Vec> = (0..4) + .map(|r| (0..8).map(|i| f64::from(r * 8 + i) * 0.01 - 0.15).collect()) + .collect(); + let x: Vec = (0..8).map(|i| 0.1 * f64::from(i) - 0.3).collect(); + let mut node = x.clone(); + if let Some((i, step)) = tied { + node[i] += step; + } + let y = w.iter().map(|row| dot(row, &node) as f32).collect(); + (w, x, y) + } + + fn dot(a: &[f64], b: &[f64]) -> f64 { + a.iter().zip(b).map(|(a, b)| a * b).sum() + } + + fn references(w: &[Vec], x: &[f64]) -> Vec<(usize, f64)> { + w.iter() + .enumerate() + .map(|(r, row)| (r, dot(row, x))) + .collect() + } + + #[test] + fn a_near_tie_explains_its_column() { + let (w, x, y) = column(Some((3, 0.5))); + let refs = references(&w, &x); + assert!(reference_error(&refs, &y, 0.0) > TOLERANCE); + let flips = [flip(1, 0.5), flip(3, 0.5), flip(5, -0.5)]; + let repair = repair(&refs, &y, 0.0, &flips, |k, f| { + f.changes.iter().map(|&(i, d)| w[k][i] * d).sum() + }) + .expect("the tie at value 3 explains the column"); + assert_eq!(repair.flips, 1); + assert!(repair.error < 1e-6, "{repair:?}"); + } + + #[test] + fn a_flip_cannot_explain_other_weights() { + // the node used other weights: every row is off by its own amount + let (w, x, mut y) = column(None); + for (r, v) in y.iter_mut().enumerate() { + *v += 0.02 * (r as f32 + 1.0) * if r % 2 == 0 { 1.0 } else { -1.0 }; + } + let refs = references(&w, &x); + assert!(reference_error(&refs, &y, 0.0) > TOLERANCE); + let flips: Vec = (0..8).map(|i| flip(i, 0.5)).collect(); + let effect = |k: usize, f: &Flip| f.changes.iter().map(|&(i, d)| w[k][i] * d).sum(); + assert_eq!(repair(&refs, &y, 0.0, &flips, effect), None); + } + + #[test] + fn two_near_ties_are_repaired_together() { + let (w, x, _) = column(None); + let mut moved = x.clone(); + moved[2] += 0.25; + moved[6] -= 0.25; + let y: Vec = w.iter().map(|row| dot(row, &moved) as f32).collect(); + let refs = references(&w, &x); + let flips = [flip(2, 0.25), flip(4, 0.25), flip(6, -0.25)]; + let effect = |k: usize, f: &Flip| f.changes.iter().map(|&(i, d)| w[k][i] * d).sum(); + let repair = repair(&refs, &y, 0.0, &flips, effect).expect("two ties explain it"); + assert_eq!(repair.flips, 2); + } + + #[test] + fn no_flips_no_repair() { + let (w, x, y) = column(Some((3, 0.5))); + let refs = references(&w, &x); + assert_eq!(repair(&refs, &y, 0.0, &[], |_, _| 0.0), None); + } +} diff --git a/crates/skippy-receipts/src/audit/pairs.rs b/crates/skippy-receipts/src/audit/pairs.rs new file mode 100644 index 00000000..06264439 --- /dev/null +++ b/crates/skippy-receipts/src/audit/pairs.rs @@ -0,0 +1,92 @@ +//! The (token, expert) pairs whose expert matmuls an audit checks. +//! +//! A MoE layer routes each opened token to several experts, and checking +//! rows of every expert used costs a fetch per expert: 21 to 26 seconds on +//! large MoE models from Hugging Face (RECEIPTS_MEASUREMENTS.md, "Row fetch"). So an +//! audit checks [`PAIRS_PER_LAYER`] pairs drawn from those the opened +//! tokens were routed to, from the rows seed. The router is still checked +//! whole, so the routing itself is checked at every opened token, and the +//! glue check still combines every opened expert output. + +use std::collections::BTreeSet; + +use crate::draw::DrawStream; +use crate::wire::LayerOpening; + +/// Pairs checked per MoE layer. +pub(crate) const PAIRS_PER_LAYER: usize = 16; + +/// The pairs of `opening` to check, as (position, expert), or `None` when +/// the layer has no expert matmul. +pub(crate) fn picked_pairs(opening: &LayerOpening, seed: &[u8]) -> Option> { + let routed: BTreeSet<(u32, i32)> = opening + .leaves + .iter() + .flat_map(|leaf| { + leaf.matrices + .iter() + .filter_map(|m| m.experts.as_ref()) + .flatten() + .map(move |&expert| (leaf.position, expert)) + }) + .collect(); + if routed.is_empty() { + return None; + } + if routed.len() <= PAIRS_PER_LAYER { + return Some(routed); + } + let routed: Vec<(u32, i32)> = routed.into_iter().collect(); + let mut stream = DrawStream::new(seed, &format!("pairs/{}", opening.layer)); + let mut picked = BTreeSet::new(); + while picked.len() < PAIRS_PER_LAYER { + picked.insert(routed[stream.below(routed.len() as u64) as usize]); + } + Some(picked) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn opening(tokens: u32, experts: i32) -> LayerOpening { + let leaf = |position: u32| { + let ids: Vec = (0..experts).map(|e| (e + position as i32) % 64).collect(); + serde_json::json!({ + "position": position, "residual_in": "", "residual_out": null, + "residual_in_path": [], "mixing_path": [], "residual_out_path": [], + "mixing": [], "selections": [], + "matrices": [ + {"index": 0, "weight": "blk.3.ffn_gate_inp.weight", "router": true, "input": "", "output": ""}, + {"index": 1, "weight": "blk.3.ffn_up_exps.weight", "experts": ids, "input": "", "output": ""}, + ], + }) + }; + serde_json::from_value(serde_json::json!({ + "layer": 3, + "leaves": (0..tokens).map(leaf).collect::>(), + })) + .unwrap() + } + + #[test] + fn pairs_are_drawn_from_the_routed_ones() { + let opening = opening(4, 8); + let picked = picked_pairs(&opening, b"seed").unwrap(); + assert_eq!(picked.len(), PAIRS_PER_LAYER); + for &(position, expert) in &picked { + assert!(position < 4); + assert!((0..8).contains(&(expert - position as i32))); + } + assert_eq!(picked_pairs(&opening, b"seed"), Some(picked.clone())); + assert_ne!(picked_pairs(&opening, b"other"), Some(picked)); + } + + #[test] + fn few_routed_pairs_are_all_checked_and_a_dense_layer_has_none() { + assert_eq!(picked_pairs(&opening(2, 4), b"seed").unwrap().len(), 8); + let dense: LayerOpening = + serde_json::from_value(serde_json::json!({"layer": 0, "leaves": []})).unwrap(); + assert_eq!(picked_pairs(&dense, b"seed"), None); + } +} diff --git a/crates/skippy-receipts/src/audit/rounding_flips.rs b/crates/skippy-receipts/src/audit/rounding_flips.rs new file mode 100644 index 00000000..86bdbe79 --- /dev/null +++ b/crates/skippy-receipts/src/audit/rounding_flips.rs @@ -0,0 +1,189 @@ +//! The roundings of an activation that a backend may take the other way. +//! +//! The client normalizes a residual in f64 and the node in f32, so their +//! activations differ by a few ulps. Where a value lies that close to a +//! rounding boundary of a profile (a q8 step, or an f16 midpoint), the two +//! sides round it apart, and the node's matmul output differs from the +//! client's reference by one step of that value times its weight column. +//! Over a whole output matrix that is far above the head key's tolerance, +//! though the node computed honestly. Few values lie that close: with q8, +//! under one per 2,560-wide activation on average. + +use std::collections::HashSet; + +use crate::activation_rounding::Profile; +use crate::error_bound::worst_of; + +/// How far, relative to its magnitude, a value may sit from the client's +/// and still be the node's: 8 f32 ulps. +const SLACK: f32 = 8.0 * f32::EPSILON; + +/// Flips of one activation past which a repair tries only single ones: +/// pairs cost the square of the count. The row check's repair and the +/// output head's key check share this bound. +pub(crate) const PAIRED_FLIPS: usize = 32; + +/// An activation the profile gives when one value moves by up to +/// [`SLACK`]: the changed outputs, as (index, change). +#[derive(Clone, Debug, PartialEq)] +pub struct Flip { + pub changes: Vec<(usize, f64)>, +} + +/// The values of a block of a profile's activation that share a scale. +fn block_len(profile: Profile) -> usize { + match profile { + Profile::Raw + | Profile::F16 + | Profile::F16Weights + | Profile::MetalTensor + | Profile::Bf16 => 1, + Profile::Q8Mul64F32 => 64, + Profile::CpuQ8K => 256, + Profile::Q8DivHalf + | Profile::Q8MulHalf + | Profile::Q8MulHalfSums + | Profile::Q8MulHalfSumsDp4a + | Profile::Q8MulF32 + | Profile::CpuQ8 => 32, + } +} + +/// The flips of `profile` at `x`, whose activation is `applied`. A value's +/// move changes its block's scale when it is the block's largest, so a flip +/// may change the whole block. Changes as small as the move itself are not +/// flips. +pub fn flips(profile: Profile, x: &[f32], applied: &[f64]) -> Vec { + let len = block_len(profile); + let mut out = Vec::new(); + // the flips found so far, by the bits of their changes: an activation + // can have thousands, and comparing each new one with all of them + // would cost their square + let mut seen: HashSet> = HashSet::new(); + for (b, block) in x.chunks(len).enumerate() { + let first = b * len; + let base = &applied[first..first + block.len()]; + let mut moved = block.to_vec(); + for i in 0..block.len() { + for factor in [1.0 + SLACK, 1.0 - SLACK] { + moved[i] = block[i] * factor; + let changes: Vec<(usize, f64)> = profile + .apply(&moved) + .iter() + .zip(base) + .enumerate() + .filter(|&(_, (a, b))| (a - b).abs() > 4.0 * f64::from(SLACK) * b.abs()) + .map(|(j, (a, b))| (first + j, a - b)) + .collect(); + if changes.is_empty() { + continue; + } + let bits = changes.iter().map(|&(j, c)| (j, c.to_bits())).collect(); + if seen.insert(bits) { + out.push(Flip { changes }); + } + } + moved[i] = block[i]; + } + } + out +} + +/// The flips that best explain `residuals`, at most two of them, and the +/// largest residual they leave. `effects[f][k]` is what flip `f` adds to the +/// reference of residual `k`. No flip is taken unless it leaves less than +/// none does, and pairs are tried only up to [`PAIRED_FLIPS`] flips. +pub(crate) fn best_explanation(residuals: &[f64], effects: &[Vec]) -> (Vec, f64) { + let left = |taken: &[usize]| { + worst_of( + residuals + .iter() + .enumerate() + .map(|(k, &e)| (e - taken.iter().map(|&f| effects[f][k]).sum::()).abs()), + ) + }; + let mut best = (Vec::new(), left(&[])); + let mut consider = |taken: Vec| { + let error = left(&taken); + if error < best.1 { + best = (taken, error); + } + }; + for a in 0..effects.len() { + consider(vec![a]); + if effects.len() <= PAIRED_FLIPS { + for b in a + 1..effects.len() { + consider(vec![a, b]); + } + } + } + best +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_on_a_q8_step_boundary_flips_alone() { + let mut x = vec![0.25f32; 32]; + x[0] = 1.27; + // d = 0.01: 0.255 lies on the boundary between steps 25 and 26 + x[5] = 0.255; + let applied = Profile::Q8DivHalf.apply(&x); + let flips = flips(Profile::Q8DivHalf, &x, &applied); + assert!( + flips + .iter() + .any(|f| f.changes.len() == 1 && f.changes[0].0 == 5) + ); + assert!(flips.iter().all(|f| f.changes.iter().all(|&(j, _)| j == 5))); + } + + #[test] + fn few_values_of_an_activation_flip() { + let mut stream = crate::draw::DrawStream::new(b"flips", "x"); + let x: Vec = (0..2560) + .map(|_| (stream.below(1 << 20) as f32 / (1 << 19) as f32) - 1.0) + .collect(); + assert!(flips(Profile::Raw, &x, &Profile::Raw.apply(&x)).is_empty()); + for profile in [Profile::Q8DivHalf, Profile::Q8MulHalf, Profile::Q8MulF32] { + let found = flips(profile, &x, &profile.apply(&x)); + assert!(found.len() < 8, "{profile:?}: {}", found.len()); + } + } + + #[test] + fn many_flips_are_each_found_once_in_order() { + // an activation a node could open to make every value a near-tie: + // each one halfway between two f16 values + let x: Vec = (0..4096) + .map(|i| 1.0 + 2f32.powi(-11) + i as f32 * 2f32.powi(-10) * 2.0) + .map(|v| v.min(1.9)) + .collect(); + let found = flips(Profile::F16, &x, &Profile::F16.apply(&x)); + assert!(found.len() > 400, "{}", found.len()); + let mut seen = HashSet::new(); + for flip in &found { + let bits: Vec<(usize, u64)> = flip + .changes + .iter() + .map(|&(j, c)| (j, c.to_bits())) + .collect(); + assert!(seen.insert(bits), "a flip was found twice: {flip:?}"); + } + let first: Vec = found.iter().map(|f| f.changes[0].0).collect(); + assert!(first.windows(2).all(|pair| pair[0] <= pair[1])); + } + + #[test] + fn an_f16_midpoint_flips() { + // halfway between the f16 values 1.0 and 1.0 + 2^-10 + let x = [1.0f32 + 2f32.powi(-11), 0.5]; + let applied = Profile::F16.apply(&x); + let found = flips(Profile::F16, &x, &applied); + assert_eq!(found.len(), 1); + assert_eq!(found[0].changes.len(), 1); + assert_eq!(found[0].changes[0].0, 0); + } +} diff --git a/crates/skippy-receipts/src/audit/row_check_tests.rs b/crates/skippy-receipts/src/audit/row_check_tests.rs new file mode 100644 index 00000000..537e094d --- /dev/null +++ b/crates/skippy-receipts/src/audit/row_check_tests.rs @@ -0,0 +1,172 @@ +//! The row check on layers of an honest toy turn, and on what a node could +//! make of them. + +use crate::audit::{MatmulPlan, Routers, allowed_failing_columns, check_rows}; +use crate::glue::check_glue; +use crate::node_fault::NodeFault; +use crate::toy_turn::{ToyModel, Turn, weights, weights_out_of_reach}; +use crate::wire::{LayerOpening, encode_f32}; + +const SEED: &[u8] = b"rows seed"; + +/// Layer 1 of an honest turn at four positions, and the auditor's plan of +/// it. +fn layer() -> (LayerOpening, MatmulPlan) { + let turn = Turn::new(); + let challenge = turn.challenge(&[(1, &[0, 1, 3, 4])], &[]); + let layer = turn.open(&challenge).stages[1].layers.remove(0); + let plan = check_glue(&ToyModel, &layer).unwrap().matmuls; + (layer, plan) +} + +#[test] +fn an_honest_layer_passes_its_row_checks() { + let (layer, plan) = layer(); + let report = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap(); + assert!(report.pass, "{:?}", report.matrices); + let names: Vec<&str> = report.matrices.iter().map(|m| m.weight.as_str()).collect(); + assert_eq!( + names, + ["blk.1.a.weight", "blk.1.exps.weight", "blk.1.router.weight"] + ); + // one column per position, and one per expert used + let columns: Vec = report.matrices.iter().map(|m| m.tokens).collect(); + assert_eq!(columns, [4, 8, 4]); + assert!(report.matrices.iter().all(|m| m.failing_tokens == 0)); +} + +#[test] +fn copies_of_a_matmul_do_not_pad_the_fail_rule() { + // The attack: every position cheats on `a`, which fails four columns + // of four. Each position then opens 31 more copies of an honest column + // of it, so 4 failures of 128 are within the 2 + n/32 the rule allows + // a matrix. + let (mut layer, plan) = layer(); + for leaf in &mut layer.leaves { + let honest = leaf.matrices[0].clone(); + leaf.matrices[0].output = encode_f32(&[9.0, 9.0, 9.0, 9.0]); + leaf.matrices.extend(vec![honest; 31]); + } + assert!(4 <= allowed_failing_columns(4 * 32)); + let error = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + assert!(format!("{error:#}").contains("more than once"), "{error:#}"); + // without the copies the cheated matmul fails + let (mut layer, plan) = self::layer(); + for leaf in &mut layer.leaves { + leaf.matrices[0].output = encode_f32(&[9.0, 9.0, 9.0, 9.0]); + } + let report = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap(); + let a = &report.matrices[0]; + assert_eq!((a.tokens, a.failing_tokens, a.pass), (4, 4, false)); +} + +#[test] +fn the_router_flag_comes_from_the_plan_and_not_the_node() { + // A node clears the flag of its router to have 16 rows checked instead + // of all, or sets it everywhere to make the client read every row of + // every weight. Neither is read. + let (mut layer, plan) = layer(); + for leaf in &mut layer.leaves { + for m in &mut leaf.matrices { + m.router = !m.router; + } + } + let report = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap(); + let routers: Vec<(&str, bool)> = report + .matrices + .iter() + .map(|m| (m.weight.as_str(), m.router)) + .collect(); + assert_eq!( + routers, + [ + ("blk.1.a.weight", false), + ("blk.1.exps.weight", false), + ("blk.1.router.weight", true) + ] + ); +} + +#[test] +fn a_matmul_the_layer_does_not_have_is_the_nodes_fault() { + let (mut layer, plan) = layer(); + layer.leaves[0].matrices[2].index = 7; + let error = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + // a weight of the same shape under the matmul's index + let (mut layer, plan) = self::layer(); + layer.leaves[0].matrices[0].weight = "blk.0.a.weight".into(); + let error = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + // every matmul left out + let (mut layer, plan) = self::layer(); + layer.leaves.iter_mut().for_each(|l| l.matrices.clear()); + let error = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} + +#[test] +fn a_column_that_is_not_a_number_or_does_not_fit_is_the_nodes_fault() { + for output in [ + encode_f32(&[f32::NAN, 0.0, 0.0, 0.0]), + encode_f32(&[f32::INFINITY, 0.0, 0.0, 0.0]), + encode_f32(&[1.0, 2.0, 3.0]), + "not base64".to_owned(), + ] { + let (mut layer, plan) = layer(); + layer.leaves[1].matrices[0].output = output.clone(); + let error = + check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{output}: {error:#}"); + } +} + +#[test] +fn a_weight_the_client_cannot_read_blames_nobody() { + let (layer, plan) = layer(); + let error = check_rows( + &weights_out_of_reach(), + &layer, + Routers::Planned(&plan), + SEED, + "CPU", + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); + // nor does a backend without rounding profiles + let error = check_rows(&weights(), &layer, Routers::Planned(&plan), SEED, "MTL0").unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} + +#[test] +fn without_a_plan_no_matmul_is_taken_for_a_router_and_a_bad_column_still_fails() { + // The auditor could not evaluate the layer, so it has no plan. The + // opening then does not get to say which weights are read whole. + let (mut layer, _) = layer(); + for leaf in &mut layer.leaves { + for m in &mut leaf.matrices { + m.router = true; + } + } + let report = check_rows(&weights(), &layer, Routers::Unknown, SEED, "CPU").unwrap(); + assert!(report.pass, "{:?}", report.matrices); + assert!(report.matrices.iter().all(|m| !m.router)); + // a column that is not the weight's still fails + for leaf in &mut layer.leaves { + leaf.matrices[0].output = encode_f32(&[9.0, 9.0, 9.0, 9.0]); + } + let report = check_rows(&weights(), &layer, Routers::Unknown, SEED, "CPU").unwrap(); + assert_eq!(report.matrices[0].failing_tokens, 4); + assert!(!report.pass); + // and a copy of a matmul, or a weight the GGUF does not have, is the + // node's fault with or without a plan + let copy = layer.leaves[0].matrices[1].clone(); + layer.leaves[0].matrices.push(copy); + let error = check_rows(&weights(), &layer, Routers::Unknown, SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + let (mut layer, _) = self::layer(); + layer.leaves[0].matrices[0].weight = "blk.1.none.weight".into(); + let error = check_rows(&weights(), &layer, Routers::Unknown, SEED, "CPU").unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} diff --git a/crates/skippy-receipts/src/audit/tests.rs b/crates/skippy-receipts/src/audit/tests.rs new file mode 100644 index 00000000..b7c7daef --- /dev/null +++ b/crates/skippy-receipts/src/audit/tests.rs @@ -0,0 +1,261 @@ +use super::*; + +fn verdict_of(weight: &str, tokens: usize, failing: usize) -> MatrixVerdict { + MatrixVerdict { + weight: weight.into(), + weight_type: "q8_0".into(), + router: weight.contains("gate_inp"), + exact: weight.contains("gate_inp"), + tokens, + failing_tokens: failing, + past_cap: 0, + repaired_tokens: 0, + max_error: 0.0, + best_profile: "raw", + pass: failing <= allowed_failing_columns(tokens), + } +} + +fn report(layer: u32, matrices: Vec) -> AuditReport { + AuditReport { + layer, + tokens: 4, + pass: matrices.iter().all(|m| m.pass), + matrices, + } +} + +#[test] +fn a_role_is_judged_on_every_opened_layer() { + // cheating on half the positions: two of four columns fail in each + // layer, which each layer alone would let pass + let reports: Vec = (0..4) + .map(|l| { + report( + l, + vec![ + verdict_of(&format!("blk.{l}.attn_q.weight"), 4, 2), + verdict_of(&format!("blk.{l}.ffn_up.weight"), 4, 0), + ], + ) + }) + .collect(); + assert!(reports.iter().all(|r| r.pass)); + let roles = pool_roles(&reports); + assert_eq!(roles.len(), 2); + assert_eq!(roles[0].role, "attn_q.weight"); + assert_eq!((roles[0].tokens, roles[0].failing_tokens), (16, 8)); + assert!(!roles[0].pass); + assert_eq!(roles[0].layers, vec![0, 1, 2, 3]); + assert!(roles[1].pass); +} + +#[test] +fn honest_outliers_spread_over_layers_still_pass() { + let reports = [ + report(3, vec![verdict_of("blk.3.attn_k.weight", 4, 1)]), + report(9, vec![verdict_of("blk.9.attn_k.weight", 4, 1)]), + report(20, vec![verdict_of("blk.20.ffn_gate_inp.weight", 4, 1)]), + ]; + let roles = pool_roles(&reports); + assert!(roles[0].pass, "{roles:?}"); + // a router may not fail a single column + assert!(roles[1].router && !roles[1].pass); +} + +#[test] +fn roles_drop_only_a_layer_prefix() { + assert_eq!( + weight_role("blk.12.ffn_down_exps.weight"), + "ffn_down_exps.weight" + ); + assert_eq!(weight_role("output.weight"), "output.weight"); + assert_eq!(weight_role("blk.x.attn_q.weight"), "blk.x.attn_q.weight"); +} + +#[test] +fn a_matrix_fails_on_a_few_bad_columns() { + // decode tokens are often a small share of a turn's positions; a + // node that cheats on four of 16 must fail + assert!(4 > allowed_failing_columns(16)); + assert_eq!(allowed_failing_columns(16), 2); + assert_eq!(allowed_failing_columns(128), 6); +} + +#[test] +fn exact_columns_have_zero_error() { + let (a, b) = ([1.0, 2.0], [-1.0, 0.5]); + let rows = vec![(0, &a[..]), (1, &b[..])]; + let x = [0.5f32, 0.25]; + let y = [1.0f32, -0.375]; + assert_eq!(column_error(&rows, &Profile::Raw.apply(&x), &y), 0.0); +} + +#[test] +fn a_wrong_output_shows_up() { + let a = [1.0, 2.0]; + let rows = vec![(0, &a[..])]; + let y = [1.01f32, 5.0]; + assert!(column_error(&rows, &Profile::Raw.apply(&[0.5, 0.25]), &y) > TOLERANCE); +} + +#[test] +fn a_huge_value_in_an_undrawn_row_hides_no_other_weights() { + // The dead-neuron cheat: a node serves gate and up from other weights + // (1.2% off, as Q6_K is from Q8_0) and opens gate = -1e6 and up = 1e6 + // at one row r. silu(-1e6) is 0, so the input of ffn_down is still + // what its glue check computes, and r is drawn only 16 times in 256. + // The error used to be relative to every opened output, r's among + // them, so 1e6 hid the 1.2% from every drawn row. + let (k, m) = (32, 256); + let w: Vec> = (0..m) + .map(|r| { + (0..k) + .map(|i| ((r * 31 + i * 17) % 23) as f64 / 50.0 - 0.22) + .collect() + }) + .collect(); + let x: Vec = (0..k).map(|i| (i * 7 % 13) as f32 / 10.0 - 0.6).collect(); + let xs = Profile::Raw.apply(&x); + for (weight, huge) in [ + ("blk.3.ffn_gate.weight", -1e6f32), + ("blk.3.ffn_up.weight", 1e6), + ] { + let picked = RowCache::default().picked(weight, m, false, b"rows seed"); + let rows: Vec<(usize, &[f64])> = picked.iter().map(|&r| (r, w[r].as_slice())).collect(); + let mut y: Vec = w + .iter() + .enumerate() + .map(|(r, row)| { + let other = if r % 2 == 0 { 1.012 } else { 0.988 }; + (row.iter().zip(&xs).map(|(a, b)| a * b).sum::() * other) as f32 + }) + .collect(); + assert!(column_error(&rows, &xs, &y) > TOLERANCE, "{weight}"); + let r = (0..m) + .find(|r| !picked.contains(r)) + .expect("an undrawn row"); + y[r] = huge; + let error = column_error(&rows, &xs, &y); + assert!(error > TOLERANCE, "{weight}: hidden at {error:e}"); + // the honest column at that row still passes + let honest: Vec = w + .iter() + .map(|row| row.iter().zip(&xs).map(|(a, b)| a * b).sum::() as f32) + .collect(); + assert!(column_error(&rows, &xs, &honest) < 1e-6); + } +} + +fn tensor(dims: Vec) -> TensorInfo { + TensorInfo { + name: "w".into(), + dims, + ggml_type: 0, + offset: 0, + } +} + +fn matrix(experts: Option>) -> MatrixOpening { + MatrixOpening { + index: 0, + weight: "w".into(), + router: false, + experts, + input: String::new(), + output: String::new(), + } +} + +#[test] +fn expert_slices_start_at_their_expert() { + let w = tensor(vec![4, 3, 8]); + let s = matmul_slices(&w, &matrix(Some(vec![5, 2])), 4, 6).unwrap(); + assert_eq!(s.slices, vec![(15, 0), (6, 0)]); + let s = matmul_slices(&w, &matrix(Some(vec![5, 2])), 8, 6).unwrap(); + assert_eq!(s.slices, vec![(15, 0), (6, 1)]); + assert!(matmul_slices(&w, &matrix(Some(vec![9, 2])), 4, 6).is_err()); + assert!(matmul_slices(&w, &matrix(Some(vec![1])), 4, 6).is_err()); +} + +#[test] +fn a_shared_weight_meets_every_batch() { + let s = matmul_slices(&tensor(vec![4, 3]), &matrix(None), 8, 6).unwrap(); + assert_eq!(s.slices, vec![(0, 0), (0, 1)]); + let s = matmul_slices(&tensor(vec![4, 3, 2]), &matrix(None), 8, 6).unwrap(); + assert_eq!(s.slices, vec![(0, 0), (3, 1)]); + assert!(matmul_slices(&tensor(vec![4, 3]), &matrix(None), 5, 3).is_err()); + // an empty column would be compared with nothing, and pass + assert!(matmul_slices(&tensor(vec![4, 3]), &matrix(None), 0, 0).is_err()); +} + +#[test] +fn an_error_that_is_not_a_number_fails_its_column() { + let weights = crate::toy_turn::weights(); + let check = |error| ColumnCheck { + error, + profile: "raw", + flips: 0, + }; + // `error > TOLERANCE` is false for NaN, so these columns used to pass + let checks = [check(0.0), check(f64::NAN), check(f64::INFINITY)]; + let router = verdict(&weights, "blk.0.router.weight".into(), true, &checks).unwrap(); + assert_eq!(router.failing_tokens, 2); + assert_eq!(router.max_error, f64::INFINITY); + assert!(!router.pass); + // three bad columns of three is past what a matrix may fail + let bad = [check(f64::NAN); 3]; + let dense = verdict(&weights, "blk.0.a.weight".into(), false, &bad).unwrap(); + assert_eq!((dense.failing_tokens, dense.pass), (3, false)); + let fine = verdict(&weights, "blk.0.a.weight".into(), false, &[check(1e-9)]).unwrap(); + assert!(fine.pass); +} + +#[path = "row_check_tests.rs"] +mod row_check_tests; + +#[test] +fn a_column_far_past_the_tolerance_fails_its_role_whatever_the_allowance() { + // two columns of 16 may fail, but not by any amount: other weights on + // two positions passed every audit + let weights = crate::toy_turn::weights(); + let check = |error| ColumnCheck { + error, + profile: "raw", + flips: 0, + }; + let mut checks = vec![check(1e-7); 16]; + checks[3] = check(2.5e-3); + checks[9] = check(3e-3); + let honest = verdict(&weights, "blk.0.a.weight".into(), false, &checks).unwrap(); + assert!(honest.pass && honest.past_cap == 0, "{honest:?}"); + checks[9] = check(0.5); + let cheat = verdict(&weights, "blk.0.a.weight".into(), false, &checks).unwrap(); + assert_eq!( + (cheat.failing_tokens, cheat.past_cap, cheat.pass), + (2, 1, false) + ); + // the role pools it with the other layers' columns and still fails + let roles = pool_roles(&[report(0, vec![cheat]), report(5, vec![honest])]); + assert_eq!((roles[0].tokens, roles[0].past_cap), (32, 1)); + assert!(!roles[0].pass); +} + +#[test] +fn only_a_router_of_float_weights_may_fail_no_column() { + use crate::ggml_types::{GGML_BF16, GGML_F16, GGML_F32, GGML_Q4_K, GGML_Q8_0}; + for float in [GGML_F32, GGML_F16, GGML_BF16] { + assert!(exact_router(true, float)); + assert!(!exact_router(false, float)); + } + // a quantized router rounds as other quantized weights do: at the + // measured 1 in 8,350 honest column failures, no allowance failed an + // honest node about 1 in 400 audits + for quantized in [GGML_Q8_0, GGML_Q4_K] { + assert!(!exact_router(true, quantized)); + } + let mut quantized = verdict_of("blk.4.ffn_gate_inp.weight", 16, 1); + quantized.exact = false; + let roles = pool_roles(&[report(4, vec![quantized])]); + assert!(roles[0].router && roles[0].pass, "{roles:?}"); +} diff --git a/crates/skippy-receipts/src/binding.rs b/crates/skippy-receipts/src/binding.rs new file mode 100644 index 00000000..02a5a36f --- /dev/null +++ b/crates/skippy-receipts/src/binding.rs @@ -0,0 +1,483 @@ +//! Client-side checks that bind a receipt to the model and the request, +//! and an opening to the receipt. +//! +//! - **Shape:** the receipt's stages cover every layer of the claimed +//! model, from 0, without gaps; each stage names the leaf count its +//! positions and layers make; it holds a token for every position; and +//! every stage commits a cached prefix exactly when the turn starts +//! after position 0. +//! - **Form:** an opening has one form for a challenge ([`canonical`]): +//! the receipt's stages, the picked layers and positions, and nothing +//! else. So nothing in it escapes the checks below. +//! - **Paths:** every opened leaf hashes to its stage root along a path of +//! the shape that tree has. This covers each picked layer, the input of +//! layer 0 with its token (the anchor), the residual leaves at stage +//! boundaries, which must be equal on both sides, the residual the +//! output head reads at every head position, and the mixing leaves of a +//! recurrent region. +//! - **Prefix:** a picked position of the turn's cached prefix is in no +//! stage tree. The stage opens every leaf it committed when it computed +//! the position, by hash. Their digest, with the cell and the digest of +//! the rows the cell stores, must be a leaf of the prefix tree the +//! receipt commits, and every opened leaf of the position must be one of +//! them ([`prefix`]). The tokens of the prefix must hash to the digest +//! the stage that holds layer 0 committed. +//! +//! [`verify_paths`] returns the opening as a [`VerifiedOpening`]. The +//! checks of the opened values take that, so they cannot run on values +//! that were not checked against a root. + +use anyhow::{Context, Result, bail}; + +use crate::commitment::{ + hex_array, leaf_index, mixing_leaf, mixing_slot, residual_leaf, residual_slot, root_from_path, + slots_per_position, +}; +use crate::layer_tensors::f32_bytes; +use crate::node_fault::{BlameNode, ensure_node}; +use crate::wire::{ + AnchorOpening, BoundaryLeaf, Challenge, HeadOpening, LayerOpening, MixingKind, Opening, + RECEIPT_VERSION, Receipt, StageCommitment, StageOpening, TensorOpening, mixing_bytes, + mixing_values, +}; + +mod canonical; +mod prefix; +mod verified; + +use prefix::PrefixLeaves; + +pub(crate) use canonical::check_mixing as check_mixing_order; +pub use verified::VerifiedOpening; + +/// Checks the receipt against the claimed model: version, stages that +/// cover layers `0..layer_count` in order, each stage's leaf count, a +/// token for every position, and a prefix commitment per stage exactly +/// when the turn continues a cached prefix. `layer_count` comes from the +/// client's own planner for the claimed GGUF, never from the receipt. +/// +/// But for the version, a receipt that fails this is the node's fault: it +/// signed a receipt that does not describe a turn of the claimed model. +pub fn verify_shape(receipt: &Receipt, layer_count: u32) -> Result<()> { + if receipt.version != RECEIPT_VERSION { + bail!( + "receipt version {} is not {RECEIPT_VERSION}", + receipt.version + ); + } + let span = receipt + .position_end + .checked_sub(receipt.position_start) + .filter(|&span| span > 0) + .context("the receipt covers no positions") + .or_node_fault()?; + // a sequence position is an i32 in the runtime + ensure_node!( + i32::try_from(receipt.position_end).is_ok(), + "the receipt ends at position {}, past any sequence", + receipt.position_end + ); + ensure_node!( + receipt.tokens.len() == span as usize, + "the receipt holds {} tokens for {span} positions", + receipt.tokens.len() + ); + ensure_node!( + (receipt.position_start..=receipt.position_end).contains(&receipt.generation_start), + "generation starts at {}, outside positions {}..{}", + receipt.generation_start, + receipt.position_start, + receipt.position_end + ); + // An honest stage always computes the last prompt token again: a + // cached prefix covers at most all the prompt but it (`backend.rs` and + // `token_generation.rs` of skippy-serving look up `prompt[..len - 1]`). + // So the first sampled token comes from a position the receipt covers; + // a turn that starts with a sampled token hides where it came from. + ensure_node!( + receipt.generation_start > receipt.position_start + || receipt.generation_start == receipt.position_end, + "the turn samples its first token from position {}, before its own positions {}..{}", + receipt.generation_start.saturating_sub(1), + receipt.position_start, + receipt.position_end + ); + let mut next = 0; + for (i, stage) in receipt.stages.iter().enumerate() { + ensure_node!( + stage.stage_index as usize == i && stage.layer_start == next && stage.layer_end > next, + "stage {} covers layers {}..{}; the stages must cover 0..{layer_count} in order", + stage.stage_index, + stage.layer_start, + stage.layer_end + ); + let leaves = u64::from(span) * slots_per_position(stage.layer_start, stage.layer_end); + ensure_node!( + stage.leaf_count == leaves, + "stage {} names {} leaves; its positions and layers make {leaves}", + stage.stage_index, + stage.leaf_count + ); + verify_prefix(receipt, stage)?; + next = stage.layer_end; + } + ensure_node!( + next == layer_count, + "the receipt covers layers 0..{next}; the claimed model has {layer_count}" + ); + Ok(()) +} + +/// A stage commits the cells of a cached prefix exactly when the turn +/// starts after position 0, one per position below the turn. The stage +/// that holds layer 0 commits the prefix's tokens with them, and no other +/// stage does. +fn verify_prefix(receipt: &Receipt, stage: &StageCommitment) -> Result<()> { + let committed = stage.prefix.as_ref().map(|prefix| prefix.positions); + let expected = (receipt.position_start > 0).then_some(receipt.position_start); + ensure_node!( + committed == expected, + "stage {} commits a cached prefix of {} positions; the turn starts at position {}", + stage.stage_index, + committed.map_or("no".to_owned(), |n| n.to_string()), + receipt.position_start + ); + if let Some(prefix) = &stage.prefix { + ensure_node!( + prefix.tokens.is_some() == (stage.layer_start == 0), + "stage {} {} the tokens of the cached prefix; the stage that holds layer 0 commits them", + stage.stage_index, + if prefix.tokens.is_some() { + "commits" + } else { + "does not commit" + } + ); + // an honest stage with recurrent state refuses to commit such a turn: + // the state the prefix's ubatches started from is gone, so nothing + // checks the state the turn started from + ensure_node!( + stage.recurrent_state.is_none(), + "stage {} commits a recurrent state with a cached prefix, which a stage that keeps \ + one never does", + stage.stage_index + ); + } + Ok(()) +} + +/// Checks that `opening` has the one form an answer to `challenge` has, +/// and every opened leaf against its stage root. Run [`verify_shape`] +/// first: this relies on the stages and leaf counts it checks. +/// +/// An error is the node's fault ([`crate::node_fault::NodeFault`]), unless +/// the challenge names another receipt. +pub fn verify_paths<'a>( + receipt: &'a Receipt, + challenge: &'a Challenge, + opening: &'a Opening, +) -> Result> { + if challenge.receipt_id != receipt.receipt_id { + bail!("the challenge names another receipt"); + } + canonical::check(receipt, challenge, opening)?; + verify_leaves(receipt, challenge, opening).or_node_fault()?; + Ok(VerifiedOpening::new(receipt, challenge, opening)) +} + +/// Every leaf of a canonical opening against its stage root. +fn verify_leaves(receipt: &Receipt, challenge: &Challenge, opening: &Opening) -> Result<()> { + let positions = challenge.positions(); + let mut trees = Vec::with_capacity(receipt.stages.len()); + for (stage, opened) in receipt.stages.iter().zip(&opening.stages) { + prefix::verify_tokens(receipt, stage, opened)?; + let tree = Tree::new(receipt, stage, opened)?; + for layer in &opened.layers { + verify_layer(&tree, opened, layer)?; + } + verify_anchors(&tree, opened)?; + verify_head(&tree, &opened.head)?; + trees.push(tree); + for region in &opened.recurrent { + let pick = challenge + .attention + .iter() + .find(|p| p.position == region.position && p.layer == region.layer) + .context("a canonical opening holds regions of attention picks alone")?; + crate::recurrent::verify_region(receipt, pick, region)?; + } + } + verify_boundaries(&trees, opening, &positions) +} + +/// The residual leaving the final layer at every head position, which +/// must be one the turn sampled a token from. A position of the cached +/// prefix is never one: the turn sampled nothing there. +fn verify_head(tree: &Tree<'_>, head: &[HeadOpening]) -> Result<()> { + if let Some(h) = head + .iter() + .find(|h| !tree.receipt.output_positions().contains(&h.position)) + { + bail!("head position {} sampled no token", h.position); + } + let layer = tree.stage.layer_end; + for h in head { + let values = f32_bytes(&h.residual_values()?); + tree.check( + h.position, + residual_slot(layer, tree.stage.layer_start), + residual_leaf(h.position, layer, None, Some(&values)), + &h.path, + "output residual", + )?; + } + Ok(()) +} + +/// Where a leaf sits in what a stage committed: in its tree of the turn, +/// or among the leaves of a picked position of the cached prefix. +struct Tree<'a> { + receipt: &'a Receipt, + stage: &'a StageCommitment, + root: [u8; 32], + /// By picked position of the prefix, the leaves the stage opened for + /// it, checked against the prefix tree. + prefix: std::collections::BTreeMap, +} + +impl<'a> Tree<'a> { + /// The stage's commitment, with the positions of the prefix `opened` + /// opens checked against it. + fn new( + receipt: &'a Receipt, + stage: &'a StageCommitment, + opened: &StageOpening, + ) -> Result { + Ok(Self { + prefix: prefix::verify_positions(stage, &opened.prefix)?, + ..Self::of_turn(receipt, stage)? + }) + } + + /// The stage's tree of the turn alone. + fn of_turn(receipt: &'a Receipt, stage: &'a StageCommitment) -> Result { + let root = hex_array( + &stage.root, + &format!("the root of stage {}", stage.stage_index), + )?; + Ok(Self { + receipt, + stage, + root, + prefix: std::collections::BTreeMap::new(), + }) + } + + /// The token at `position`: the receipt's for a position of the turn, + /// else the one `opened`, the opening of the stage that holds layer 0, + /// names for the prefix. + fn token(&self, opened: &StageOpening, position: u32) -> Result { + if position < self.receipt.position_start { + return opened + .prefix_tokens + .get(position as usize) + .copied() + .context("no token for the position of the prefix"); + } + self.receipt + .token_at(position) + .context("no token for the position") + } + + fn check( + &self, + position: u32, + slot: u64, + leaf: [u8; 32], + path: &[String], + what: &str, + ) -> Result<()> { + if let Some(committed) = self.prefix.get(&position) { + return committed.check(position, slot, leaf, path, what); + } + if position < self.receipt.position_start || position >= self.receipt.position_end { + bail!("position {position} is outside the receipt"); + } + let slots = slots_per_position(self.stage.layer_start, self.stage.layer_end); + let index = leaf_index(position, slot, self.receipt.position_start, slots); + if root_from_path(leaf, index, self.stage.leaf_count, path)? != self.root { + bail!( + "position {position}: the opened {what} does not match stage {}'s root", + self.stage.stage_index + ); + } + Ok(()) + } +} + +/// Checks one position's opened mixing values against the root of the +/// stage holding `layer`. +pub(crate) fn verify_mixing_leaf( + receipt: &Receipt, + layer: u32, + position: u32, + mixing: &[TensorOpening], + path: &[String], +) -> Result<()> { + let stage = receipt + .stage_for_layer(layer) + .with_context(|| format!("the receipt has no stage for layer {layer}"))?; + let decoded = mixing_bytes(mixing)?; + Tree::of_turn(receipt, stage)?.check( + position, + mixing_slot(layer, stage.layer_start), + mixing_leaf(position, layer, &mixing_values(&decoded)), + path, + "mixing values", + ) +} + +fn verify_layer(tree: &Tree<'_>, opened: &StageOpening, opening: &LayerOpening) -> Result<()> { + let (receipt, stage) = (tree.receipt, tree.stage); + let layer = opening.layer; + // only the model's final layer keeps no row for positions it does not + // output; any other layer that drops a row would skip its checks + let final_layer = layer + 1 == receipt.layer_count(); + for leaf in &opening.leaves { + let position = leaf.position; + if leaf.residual_out.is_none() && !final_layer { + bail!("position {position}: layer {layer} opened no residual out"); + } + let stored = leaf + .mixing + .iter() + .filter(|t| t.kind == MixingKind::Stored && t.values.is_some()); + for stored in stored { + let name = crate::cache_types::name(stored.ggml_type); + if !stage.cache_types.contains(&name) { + bail!( + "position {position}: a stored row is {name}, which the receipt does not name" + ); + } + } + let token = if layer == 0 { + Some(tree.token(opened, position)?) + } else { + None + }; + if let Some(committed) = tree.prefix.get(&position) { + // the rows an attention check reads from this cell are the + // ones this position's mixing leaf holds + committed.check_stored(position, layer - stage.layer_start, &leaf.mixing)?; + } + let residual_in = f32_bytes(&leaf.residual_in_values()?); + let residual_out = leaf.residual_out_values()?.map(|v| f32_bytes(&v)); + let decoded = mixing_bytes(&leaf.mixing)?; + let start = stage.layer_start; + tree.check( + position, + residual_slot(layer, start), + residual_leaf(position, layer, token, Some(&residual_in)), + &leaf.residual_in_path, + "residual-in", + )?; + tree.check( + position, + mixing_slot(layer, start), + mixing_leaf(position, layer, &mixing_values(&decoded)), + &leaf.mixing_path, + "mixing values", + )?; + tree.check( + position, + residual_slot(layer + 1, start), + residual_leaf(position, layer + 1, None, residual_out.as_deref()), + &leaf.residual_out_path, + "residual-out", + )?; + } + Ok(()) +} + +/// The input of layer 0 at every picked position, with the token the +/// receipt names for it. A stage that does not hold layer 0 opens none. +fn verify_anchors(tree: &Tree<'_>, opened: &StageOpening) -> Result<()> { + let anchors: &[AnchorOpening] = &opened.anchors; + for anchor in anchors { + let token = tree.token(opened, anchor.position)?; + if anchor.token != token { + bail!( + "position {}: the anchor holds token {}, the receipt {token}", + anchor.position, + anchor.token + ); + } + let values = f32_bytes(&anchor.residual_values()?); + tree.check( + anchor.position, + residual_slot(0, 0), + residual_leaf(anchor.position, 0, Some(token), Some(&values)), + &anchor.path, + "input of layer 0", + )?; + } + Ok(()) +} + +/// Where stage `k` hands over to stage `k + 1`, both stages commit the same +/// residual: the leaf must be the same and in both trees. The leaf leaving +/// the final stage must be in its tree. +fn verify_boundaries(trees: &[Tree<'_>], opening: &Opening, positions: &[u32]) -> Result<()> { + let stages: Vec<(&Tree<'_>, &StageOpening)> = trees.iter().zip(&opening.stages).collect(); + for pair in stages.windows(2) { + let ((below_tree, sent), (above_tree, received)) = (pair[0], pair[1]); + let (below, above) = (below_tree.stage, above_tree.stage); + let layer = below.layer_end; + for &position in positions { + let find = + |leaves: &[BoundaryLeaf]| leaves.iter().find(|b| b.position == position).cloned(); + let (Some(exit), Some(entry)) = (find(&sent.exit), find(&received.entry)) else { + bail!("position {position}: the boundary at layer {layer} was not opened"); + }; + if exit.leaf != entry.leaf { + bail!( + "position {position}: stage {} received a different residual at layer {layer} \ + than stage {} sent", + above.stage_index, + below.stage_index + ); + } + let leaf = hex_array(&exit.leaf, "a boundary leaf")?; + below_tree.check( + position, + residual_slot(layer, below.layer_start), + leaf, + &exit.path, + "residual leaving the stage", + )?; + above_tree.check( + position, + residual_slot(layer, above.layer_start), + leaf, + &entry.path, + "residual entering the stage", + )?; + } + } + if let Some((tree, opened)) = stages.last() { + let stage = tree.stage; + for exit in &opened.exit { + tree.check( + exit.position, + residual_slot(stage.layer_end, stage.layer_start), + hex_array(&exit.leaf, "a boundary leaf")?, + &exit.path, + "residual leaving the stage", + )?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/binding/canonical.rs b/crates/skippy-receipts/src/binding/canonical.rs new file mode 100644 index 00000000..707b33fd --- /dev/null +++ b/crates/skippy-receipts/src/binding/canonical.rs @@ -0,0 +1,242 @@ +//! The one form an opening of a challenge has. +//! +//! A check that looks a value up in an opening finds the first entry that +//! fits. Were an opening free to hold more than the challenge asks, a node +//! could put a decoy first: an extra stage, a second copy of a layer or a +//! position, a list in the wrong stage. The Merkle check would run on one +//! entry and the value checks on another. So an opening must hold exactly +//! what the challenge asks, in the order a stage opens it: +//! +//! - the receipt's stages, in order, by index; +//! - in each stage, the picked layers it holds, once each, in the +//! challenge's order, and in each layer the pick's positions; +//! - in each position, the mixing values in leaf order, and each matmul and +//! selection index once, in increasing order; +//! - the input of layer 0 at every picked position, on the stage that +//! holds layer 0 and on no other; +//! - the leaf entering every stage but the first, and the leaf leaving +//! every stage, at every picked position; +//! - the output residual at the head positions, on the final stage alone; +//! - attention partials and a recurrent region only for attention picks of +//! the stage's layers, once each; +//! - what the stage committed at every picked position of the cached +//! prefix, in position order, and the tokens of the whole prefix on the +//! stage that holds layer 0 and on no other. +//! +//! Every failure here is the node's fault. + +use std::collections::BTreeSet; + +use anyhow::Result; + +use crate::node_fault::ensure_node; +use crate::wire::{ + Challenge, LeafOpening, MixingKind, Opening, Receipt, StageCommitment, StageOpening, + TensorOpening, +}; + +pub(super) fn check(receipt: &Receipt, challenge: &Challenge, opening: &Opening) -> Result<()> { + ensure_node!( + opening.receipt_id == receipt.receipt_id, + "the opening names another receipt" + ); + let stages: Vec = receipt.stages.iter().map(|s| s.stage_index).collect(); + let opened: Vec = opening.stages.iter().map(|s| s.stage_index).collect(); + ensure_node!( + !stages.is_empty() && opened == stages, + "the opening holds stages {opened:?}; the receipt's stages are {stages:?}" + ); + let positions = challenge.positions(); + let prefix = challenge.prefix_positions(receipt.position_start); + let last = receipt.stages.len() - 1; + for (i, (stage, opened)) in receipt.stages.iter().zip(&opening.stages).enumerate() { + check_layers(stage, challenge, opened)?; + check_prefix(receipt, stage, opened, &prefix)?; + let none: &[u32] = &[]; + let lists = [ + ( + "the input of layer 0", + positions_of(opened.anchors.iter().map(|a| a.position)), + if stage.layer_start == 0 { + &positions + } else { + none + }, + ), + ( + "the residual entering the stage", + positions_of(opened.entry.iter().map(|b| b.position)), + if i > 0 { &positions } else { none }, + ), + ( + "the residual leaving the stage", + positions_of(opened.exit.iter().map(|b| b.position)), + &positions, + ), + ( + "the output residual", + positions_of(opened.head.iter().map(|h| h.position)), + if i == last { &challenge.head } else { none }, + ), + ]; + for (what, opened, asked) in lists { + ensure_node!( + opened == asked, + "stage {} opens {what} at {opened:?}, the challenge asks {asked:?}", + stage.stage_index + ); + } + check_attention(stage, challenge, opened)?; + } + Ok(()) +} + +fn positions_of(positions: impl Iterator) -> Vec { + positions.collect() +} + +/// The stage opens what it committed at the picked positions of the +/// prefix, and the tokens of the prefix when it holds layer 0. A list of +/// another length would let a node send what no check reads. +fn check_prefix( + receipt: &Receipt, + stage: &StageCommitment, + opened: &StageOpening, + asked: &[u32], +) -> Result<()> { + let positions = positions_of(opened.prefix.iter().map(|p| p.position)); + ensure_node!( + positions == asked, + "stage {} opens positions {positions:?} of the prefix, the challenge asks {asked:?}", + stage.stage_index + ); + let tokens = if stage.layer_start == 0 { + receipt.position_start as usize + } else { + 0 + }; + ensure_node!( + opened.prefix_tokens.len() == tokens, + "stage {} opens {} tokens of the prefix; it must open {tokens}", + stage.stage_index, + opened.prefix_tokens.len() + ); + Ok(()) +} + +/// The stage opens the picked layers it holds, in the challenge's order, +/// each at its pick's positions. +fn check_layers( + stage: &StageCommitment, + challenge: &Challenge, + opened: &StageOpening, +) -> Result<()> { + let held = stage.layer_start..stage.layer_end; + let picks: Vec<_> = challenge + .picks + .iter() + .filter(|p| held.contains(&p.layer)) + .collect(); + let asked: Vec = picks.iter().map(|p| p.layer).collect(); + let layers: Vec = opened.layers.iter().map(|l| l.layer).collect(); + ensure_node!( + layers == asked, + "stage {} opens layers {layers:?}, the challenge picks {asked:?} of its layers", + stage.stage_index + ); + for (pick, layer) in picks.iter().zip(&opened.layers) { + let positions = positions_of(layer.leaves.iter().map(|l| l.position)); + ensure_node!( + positions == pick.positions, + "layer {} opens positions {positions:?}, the challenge asked {:?}", + pick.layer, + pick.positions + ); + for leaf in &layer.leaves { + check_leaf(pick.layer, leaf)?; + } + } + Ok(()) +} + +fn check_leaf(layer: u32, leaf: &LeafOpening) -> Result<()> { + let position = leaf.position; + check_mixing(&leaf.mixing).map_err(|error| error.context(format!("position {position}")))?; + let increasing = |indices: Vec| indices.windows(2).all(|pair| pair[0] < pair[1]); + ensure_node!( + increasing(leaf.matrices.iter().map(|m| m.index).collect()), + "position {position}: layer {layer} does not open each matmul once, in order" + ); + ensure_node!( + increasing(leaf.selections.iter().map(|s| s.index).collect()), + "position {position}: layer {layer} does not open each selection once, in order" + ); + Ok(()) +} + +/// A mixing leaf lists its values by kind, in the order the leaf hashes +/// them, and within a kind by index from 0 without a gap. +pub(crate) fn check_mixing(mixing: &[TensorOpening]) -> Result<()> { + let mut previous: Option<(MixingKind, u32)> = None; + for value in mixing { + let expected = match previous { + Some((kind, index)) if kind == value.kind => index.checked_add(1), + Some((kind, _)) if kind > value.kind => None, + _ => Some(0), + }; + ensure_node!( + expected == Some(value.index), + "the mixing values are not in leaf order, each once: {:?} {} follows {previous:?}", + value.kind, + value.index + ); + previous = Some((value.kind, value.index)); + } + Ok(()) +} + +/// Partials and a recurrent region are opened only for attention picks of +/// the stage's layers: partials once per pick, and at most one region. +fn check_attention( + stage: &StageCommitment, + challenge: &Challenge, + opened: &StageOpening, +) -> Result<()> { + let held = stage.layer_start..stage.layer_end; + let picked = |position: u32, layer: u32| { + held.contains(&layer) + && challenge + .attention + .iter() + .any(|p| p.position == position && p.layer == layer) + }; + let mut seen = BTreeSet::new(); + for partials in &opened.attention { + ensure_node!( + picked(partials.position, partials.layer) + && seen.insert((partials.layer, partials.position)), + "stage {} opens attention partials at position {} of layer {}, which is not one \ + attention pick of its layers, once", + stage.stage_index, + partials.position, + partials.layer + ); + } + ensure_node!( + opened.recurrent.len() <= 1, + "stage {} opens {} recurrent regions; a stage opens one at most", + stage.stage_index, + opened.recurrent.len() + ); + for region in &opened.recurrent { + ensure_node!( + picked(region.position, region.layer), + "stage {} opens a recurrent region at position {} of layer {}, which is not an \ + attention pick of its layers", + stage.stage_index, + region.position, + region.layer + ); + } + Ok(()) +} diff --git a/crates/skippy-receipts/src/binding/prefix.rs b/crates/skippy-receipts/src/binding/prefix.rs new file mode 100644 index 00000000..848acfd1 --- /dev/null +++ b/crates/skippy-receipts/src/binding/prefix.rs @@ -0,0 +1,211 @@ +//! What a stage opens of a turn's cached prefix, against the receipt. +//! +//! A turn that continued a cached prefix computed nothing below its first +//! position, so its stage trees hold no leaf of the prefix. Each stage +//! commits the prefix apart: a tree with one leaf per position, which binds +//! the position's KV cell, the digest of the rows the cell stores, and the +//! digest of every leaf the stage committed when it computed the position +//! ([`crate::commitment::prefix_leaf`]). +//! +//! For a picked position of the prefix a stage opens those leaves, by hash, +//! and the leaves of the rows each of its layers stored in the cell +//! ([`PrefixOpening`]). [`verify_positions`] checks them against the +//! prefix root. A value the node opens at that position is then checked +//! against the leaf it must hash to, as a value of the turn is checked +//! against the stage tree. The stored rows a mixing leaf holds must be the +//! ones the cell's digest covers, because an attention check of a later +//! position reads the cell's rows through that digest. +//! +//! The stage that holds layer 0 opens the tokens of the whole prefix, which +//! must hash to the digest it committed ([`verify_tokens`]). The layer-0 +//! leaf of a picked position binds its token, so a token the node did not +//! compute the position with fails there. +//! +//! Every failure here is the node's fault. + +use std::collections::BTreeMap; + +use anyhow::{Context, Result, bail}; + +use crate::attention::opening::stored_digests; +use crate::commitment::{ + Hash, cell_digest, hex_array, position_digest, prefix_leaf, prefix_tokens_digest, + root_from_path, slots_per_position, stored_leaf, +}; +use crate::wire::{ + MixingKind, PrefixOpening, Receipt, StageCommitment, StageOpening, TensorOpening, +}; + +/// The leaves a stage committed at one picked position of the prefix, +/// checked against the prefix root. +pub(super) struct PrefixLeaves { + stage_index: u32, + /// The first layer the stage holds. + first_layer: u32, + /// The position's leaves, in slot order. + leaves: Vec, + /// The leaf of the rows each layer of the stage stored in the cell. + stored: Vec, +} + +impl PrefixLeaves { + /// Checks a leaf the node opened at the position against the one the + /// stage committed in `slot`. Such a leaf has no path: it is in no + /// tree. + pub(super) fn check( + &self, + position: u32, + slot: u64, + leaf: Hash, + path: &[String], + what: &str, + ) -> Result<()> { + if !path.is_empty() { + bail!("position {position}: the {what} of a prefix position was opened with a path"); + } + let committed = usize::try_from(slot) + .ok() + .and_then(|slot| self.leaves.get(slot)); + if committed != Some(&leaf) { + bail!( + "position {position}: the opened {what} does not match what stage {} committed \ + for the cached prefix", + self.stage_index + ); + } + Ok(()) + } + + /// Checks that the stored rows of an opened mixing leaf of the stage's + /// layer `index` are the rows the cell's digest covers. + pub(super) fn check_stored( + &self, + position: u32, + index: u32, + mixing: &[TensorOpening], + ) -> Result<()> { + let layer = self.first_layer + index; + let stored: Vec = mixing + .iter() + .filter(|value| value.kind == MixingKind::Stored) + .cloned() + .collect(); + let leaf = stored_leaf(position, layer, &stored_digests(&stored)?); + if self.stored.get(index as usize) != Some(&leaf) { + bail!( + "position {position}: the rows layer {layer} stored are not the rows of the \ + cell the prefix commits" + ); + } + Ok(()) + } +} + +/// Checks every position of the prefix `opened` holds against the prefix +/// tree `stage` commits, and returns their leaves by position. +pub(super) fn verify_positions( + stage: &StageCommitment, + opened: &[PrefixOpening], +) -> Result> { + let Some(prefix) = &stage.prefix else { + if !opened.is_empty() { + bail!( + "stage {} opens positions of a prefix it did not commit", + stage.stage_index + ); + } + return Ok(BTreeMap::new()); + }; + let root: Hash = hex_array(&prefix.root, "the prefix root")?; + let slots = slots_per_position(stage.layer_start, stage.layer_end); + let layers = stage.layer_end - stage.layer_start; + let mut verified = BTreeMap::new(); + for position in opened { + let at = position.position; + let hashes = |list: &[String], what: &str| -> Result> { + list.iter().map(|hash| hex_array(hash, what)).collect() + }; + if position.leaves.len() as u64 != slots || position.stored.len() != layers as usize { + bail!( + "position {at}: stage {} opens {} leaves and {} stored leaves; its layers make \ + {slots} and {layers}", + stage.stage_index, + position.leaves.len(), + position.stored.len() + ); + } + let leaves = hashes(&position.leaves, "a leaf of a prefix position")?; + let stored = hashes(&position.stored, "a stored leaf of a prefix cell")?; + let leaf = prefix_leaf( + i32::try_from(at).context("a prefix position past any sequence")?, + position.cell, + &cell_digest(stored.clone())?, + &position_digest(&leaves), + ); + let committed = root_from_path( + leaf, + u64::from(at), + u64::from(prefix.positions), + &position.path, + ) + .with_context(|| format!("position {at} of the prefix"))?; + if committed != root { + bail!( + "position {at}: the opened leaves do not match stage {}'s prefix root", + stage.stage_index + ); + } + verified.insert( + at, + PrefixLeaves { + stage_index: stage.stage_index, + first_layer: stage.layer_start, + leaves, + stored, + }, + ); + } + Ok(verified) +} + +/// Checks the tokens of the prefix a stage opened: the stage that holds +/// layer 0 opens one per position of the prefix, which hash to the digest +/// it committed, and no other stage opens any. +pub(super) fn verify_tokens( + receipt: &Receipt, + stage: &StageCommitment, + opened: &StageOpening, +) -> Result<()> { + let committed = stage + .prefix + .as_ref() + .and_then(|prefix| prefix.tokens.as_deref()); + let Some(committed) = committed else { + if !opened.prefix_tokens.is_empty() { + bail!( + "stage {} opens tokens of a prefix it committed none for", + stage.stage_index + ); + } + return Ok(()); + }; + if opened.prefix_tokens.len() != receipt.position_start as usize { + bail!( + "stage {} opens {} tokens of the prefix; the turn starts at position {}", + stage.stage_index, + opened.prefix_tokens.len(), + receipt.position_start + ); + } + if hex::encode(prefix_tokens_digest(&opened.prefix_tokens)) != committed { + bail!( + "the opened tokens of the prefix do not match what stage {} committed", + stage.stage_index + ); + } + Ok(()) +} + +#[cfg(test)] +#[path = "prefix_tests.rs"] +mod tests; diff --git a/crates/skippy-receipts/src/binding/prefix_tests.rs b/crates/skippy-receipts/src/binding/prefix_tests.rs new file mode 100644 index 00000000..59aaab7d --- /dev/null +++ b/crates/skippy-receipts/src/binding/prefix_tests.rs @@ -0,0 +1,164 @@ +use super::super::{verify_paths, verify_shape}; +use crate::node_fault::NodeFault; +use crate::toy_turn::{LAYERS, Turn}; +use crate::wire::{Challenge, Opening, encode_f32}; + +/// A turn that continued a prefix of 40 positions. +const PREFIX: u32 = 40; + +/// Positions 7 and 31 of the prefix and two of the turn, in both layers. +fn challenged(turn: &Turn) -> Challenge { + turn.challenge(&[(0, &[7, 31, 41, 43]), (1, &[7, 31, 40, 43])], &[42, 44]) +} + +/// The node's fault `change` makes of an honest opening of a cached turn. +fn fault(change: impl FnOnce(&mut Opening)) -> String { + let turn = Turn::starting_at(PREFIX); + let challenge = challenged(&turn); + let mut opening = turn.open(&challenge); + change(&mut opening); + let error = verify_paths(&turn.receipt, &challenge, &opening).unwrap_err(); + assert!( + NodeFault::find(&error).is_some(), + "not blamed on the node: {error:#}" + ); + format!("{error:#}") +} + +#[test] +fn an_honest_opening_of_a_cached_turn_is_verified() { + let turn = Turn::starting_at(PREFIX); + verify_shape(&turn.receipt, LAYERS).unwrap(); + let challenge = challenged(&turn); + assert_eq!(challenge.prefix_positions(PREFIX), [7, 31]); + let opening = turn.open(&challenge); + let verified = verify_paths(&turn.receipt, &challenge, &opening).unwrap(); + // a position of the prefix is opened like one of the turn + assert_eq!(verified.leaf(1, 31).unwrap().position, 31); + let anchors: Vec = verified.anchors().iter().map(|a| a.position).collect(); + assert_eq!(anchors, [7, 31, 40, 41, 43]); + assert_eq!(verified.prefix_tokens().len(), PREFIX as usize); + // a turn from position 0 opens nothing of a prefix + let fresh = Turn::new(); + let challenge = fresh.challenge(&[(0, &[1])], &[]); + let opening = fresh.open(&challenge); + assert!(opening.stages.iter().all(|s| s.prefix.is_empty())); + let verified = verify_paths(&fresh.receipt, &challenge, &opening).unwrap(); + assert!(verified.prefix_tokens().is_empty()); +} + +#[test] +fn a_value_the_prefix_did_not_commit_is_refused() { + // a residual, a mixing value and the input of layer 0 + let message = fault(|o| o.stages[1].layers[0].leaves[0].residual_in = encode_f32(&[9.0; 4])); + assert!(message.contains("position 7"), "{message}"); + assert!(message.contains("cached prefix"), "{message}"); + fault(|o| o.stages[0].layers[0].leaves[1].mixing[2].values = Some("AAAAAA==".into())); + fault(|o| o.stages[0].anchors[0].residual = encode_f32(&[9.0; 4])); + // the leaves at the stage boundary must be the ones both stages commit + fault(|o| o.stages[0].exit[0].leaf = hex::encode([3u8; 32])); + // a leaf of the prefix is in no tree: a path is not an answer + let message = fault(|o| { + let path = o.stages[0].layers[0].leaves[2].residual_in_path.clone(); + o.stages[0].layers[0].leaves[0].residual_in_path = path; + }); + assert!(message.contains("with a path"), "{message}"); +} + +#[test] +fn the_opened_leaves_of_a_prefix_position_are_bound_to_the_prefix_root() { + // an altered leaf, another cell, another position's opening + let message = fault(|o| o.stages[0].prefix[0].leaves[1] = hex::encode([3u8; 32])); + assert!(message.contains("prefix root"), "{message}"); + fault(|o| o.stages[0].prefix[0].cell += 1); + fault(|o| { + let other = o.stages[1].prefix[1].clone(); + o.stages[1].prefix[0].leaves = other.leaves; + }); + fault(|o| { + o.stages[1].prefix[0] + .path + .pop() + .map(drop) + .unwrap_or_default() + }); + // the rows the cell stores are the rows the mixing leaf holds + let message = fault(|o| o.stages[0].prefix[0].stored[0] = hex::encode([3u8; 32])); + assert!(message.contains("prefix root"), "{message}"); + // a list of another length + fault(|o| o.stages[0].prefix[0].leaves.push(hex::encode([3u8; 32]))); + fault(|o| { + o.stages[0].prefix[0].leaves.pop(); + }); + fault(|o| o.stages[1].prefix[1].stored.clear()); +} + +#[test] +fn a_prefix_position_is_opened_exactly_when_it_is_picked() { + // missing, twice, out of order, or one the challenge did not pick + let message = fault(|o| { + o.stages[0].prefix.pop(); + }); + assert!(message.contains("of the prefix"), "{message}"); + fault(|o| o.stages[1].prefix.clear()); + fault(|o| o.stages[0].prefix.swap(0, 1)); + fault(|o| { + let twice = o.stages[0].prefix[0].clone(); + o.stages[0].prefix.push(twice); + }); + fault(|o| o.stages[0].prefix[1].position = 32); + // a position of the turn is not one of the prefix + fault(|o| o.stages[0].prefix[1].position = 41); +} + +#[test] +fn the_tokens_of_the_prefix_are_bound_to_the_receipt() { + // a wrong token: the list no longer hashes to what stage 0 committed + let message = fault(|o| o.stages[0].prefix_tokens[5] += 1); + assert!(message.contains("tokens of the prefix"), "{message}"); + // a short list, a long one, and one on a stage that holds no layer 0 + let message = fault(|o| { + o.stages[0].prefix_tokens.pop(); + }); + assert!(message.contains("it must open 40"), "{message}"); + fault(|o| o.stages[0].prefix_tokens.push(1)); + fault(|o| o.stages[0].prefix_tokens.clear()); + fault(|o| o.stages[1].prefix_tokens = o.stages[0].prefix_tokens.clone()); + // the token an anchor names is the prefix's + let message = fault(|o| o.stages[0].anchors[1].token += 1); + assert!(message.contains("anchor holds token"), "{message}"); +} + +#[test] +fn a_node_that_computed_a_prefix_position_from_another_token_fails() { + // The node commits the tokens the client sent, but computed position 7 + // of the prefix from another one. The layer-0 leaf it committed binds + // the token it used, so no opening of the position matches it. + let turn = Turn::starting_at(PREFIX); + let challenge = challenged(&turn); + let honest = turn.open(&challenge); + let mut receipt = turn.receipt.clone(); + let mut tokens = honest.stages[0].prefix_tokens.clone(); + tokens[7] += 1; + receipt.stages[0].prefix.as_mut().unwrap().tokens = Some(hex::encode( + crate::commitment::prefix_tokens_digest(&tokens), + )); + let mut opening = honest; + opening.stages[0].prefix_tokens = tokens; + opening.stages[0].anchors[0].token += 1; + let error = verify_paths(&receipt, &challenge, &opening).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + assert!(format!("{error:#}").contains("position 7"), "{error:#}"); +} + +#[test] +fn a_prefix_opening_of_a_turn_without_a_prefix_is_refused() { + let cached = Turn::starting_at(PREFIX); + let stolen = cached.open(&challenged(&cached)).stages[0].prefix[0].clone(); + let turn = Turn::new(); + let challenge = turn.challenge(&[(0, &[1])], &[]); + let mut opening = turn.open(&challenge); + opening.stages[0].prefix.push(stolen); + let error = verify_paths(&turn.receipt, &challenge, &opening).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} diff --git a/crates/skippy-receipts/src/binding/tests.rs b/crates/skippy-receipts/src/binding/tests.rs new file mode 100644 index 00000000..c19c3bcf --- /dev/null +++ b/crates/skippy-receipts/src/binding/tests.rs @@ -0,0 +1,393 @@ +use super::*; +use crate::node_fault::NodeFault; +use crate::toy_turn::{LAYERS, Turn}; +use crate::wire::{LeafOpening, MixingKind, TensorOpening}; + +/// What a node changes in an honest opening. +type Change<'a> = Box; + +/// Layer 0 at positions 1 and 3, layer 1 at positions 0 and 3, and the +/// head at two output positions. +fn challenged(turn: &Turn) -> Challenge { + turn.challenge(&[(0, &[1, 3]), (1, &[0, 3])], &[2, 4]) +} + +/// The node's fault `change` makes of an honest opening. +fn fault(change: impl FnOnce(&mut Opening)) -> String { + let turn = Turn::new(); + let challenge = challenged(&turn); + let mut opening = turn.open(&challenge); + change(&mut opening); + let error = verify_paths(&turn.receipt, &challenge, &opening).unwrap_err(); + assert!( + NodeFault::find(&error).is_some(), + "not blamed on the node: {error:#}" + ); + format!("{error:#}") +} + +#[test] +fn an_honest_opening_is_verified() { + let turn = Turn::new(); + verify_shape(&turn.receipt, LAYERS).unwrap(); + let challenge = challenged(&turn); + let opening = turn.open(&challenge); + let verified = verify_paths(&turn.receipt, &challenge, &opening).unwrap(); + // the view finds what the challenge asked, and nothing else + let (layer, backend) = verified.layer(1).unwrap(); + assert_eq!((layer.layer, backend), (1, "CPU")); + assert_eq!(verified.leaf(1, 3).unwrap().position, 3); + assert!(verified.leaf(1, 1).is_none()); + assert!(verified.layer(2).is_none()); + let anchors: Vec = verified.anchors().iter().map(|a| a.position).collect(); + assert_eq!(anchors, [0, 1, 3]); + let (_, head) = verified.head().unwrap(); + assert_eq!(head.iter().map(|h| h.position).collect::>(), [2, 4]); + assert!(verified.partials(&challenge_pick(1, 3)).is_none()); + assert!(verified.region(&turn.receipt.stages[1]).is_none()); +} + +fn challenge_pick(layer: u32, position: u32) -> crate::attention::opening::AttentionPick { + crate::attention::opening::AttentionPick { + position, + layer, + head_draw: 0, + } +} + +#[test] +fn a_decoy_stage_in_front_is_refused() { + // The attack: a stage with an index the receipt does not have, put + // first, with a layer of the node's own values under a picked layer's + // number. The Merkle check looked stages up by index and skipped it; + // the value checks took the first layer that matched and read it. + let message = fault(|opening| { + let mut decoy = opening.stages[1].clone(); + decoy.stage_index = 99; + decoy.layers[0].leaves[0].residual_in = crate::wire::encode_f32(&[9.0; 4]); + opening.stages.insert(0, decoy); + }); + assert!(message.contains("stages [99, 0, 1]"), "{message}"); +} + +#[test] +fn a_stage_twice_missing_or_out_of_order_is_refused() { + fault(|opening| opening.stages.push(opening.stages[1].clone())); + fault(|opening| opening.stages.insert(1, opening.stages[0].clone())); + fault(|opening| opening.stages.swap(0, 1)); + fault(|opening| { + opening.stages.pop(); + }); + fault(|opening| opening.stages.clear()); +} + +#[test] +fn a_layer_the_challenge_did_not_pick_is_refused() { + // an extra layer of the stage's own, a second copy, one from another + // stage, and a picked layer left out + let message = fault(|opening| { + let mut extra = opening.stages[1].layers[0].clone(); + extra.layer = 0; + opening.stages[1].layers.push(extra); + }); + assert!(message.contains("opens layers [1, 0]"), "{message}"); + fault(|opening| { + let copy = opening.stages[0].layers[0].clone(); + opening.stages[0].layers.insert(0, copy); + }); + fault(|opening| { + let moved = opening.stages[0].layers.remove(0); + opening.stages[1].layers.push(moved); + }); + fault(|opening| opening.stages[1].layers.clear()); +} + +#[test] +fn a_position_twice_missing_or_unasked_is_refused() { + fn leaves(opening: &mut Opening) -> &mut Vec { + &mut opening.stages[1].layers[0].leaves + } + let message = fault(|opening| { + let copy = leaves(opening)[1].clone(); + leaves(opening).push(copy); + }); + assert!(message.contains("opens positions [0, 3, 3]"), "{message}"); + fault(|opening| leaves(opening).swap(0, 1)); + fault(|opening| { + leaves(opening).pop(); + }); + // a decoy leaf under a picked position's number, in front + fault(|opening| { + let mut decoy = leaves(opening)[1].clone(); + decoy.position = 0; + leaves(opening).insert(0, decoy); + }); +} + +#[test] +fn a_matmul_selection_or_mixing_value_twice_is_refused() { + fn leaf(opening: &mut Opening) -> &mut LeafOpening { + &mut opening.stages[0].layers[0].leaves[0] + } + // 27 copies of an honest column around one that cheats would have + // raised the row check's allowance past it + let message = fault(|opening| { + let copy = leaf(opening).matrices[0].clone(); + leaf(opening).matrices.insert(0, copy); + }); + assert!(message.contains("each matmul once"), "{message}"); + fault(|opening| leaf(opening).matrices.swap(0, 2)); + fault(|opening| { + let copy = leaf(opening).selections[0].clone(); + leaf(opening).selections.push(copy); + }); + // a second stored row under index 0, and values out of leaf order + fault(|opening| { + let copy = leaf(opening).mixing[1].clone(); + leaf(opening).mixing.insert(1, copy); + }); + fault(|opening| leaf(opening).mixing.swap(0, 2)); + fault(|opening| leaf(opening).mixing[2].index = 1); +} + +#[test] +fn mixing_values_are_in_leaf_order_from_index_zero() { + let value = |kind, index| TensorOpening::new(kind, index, None); + let (input, stored, output, state) = ( + MixingKind::Input, + MixingKind::Stored, + MixingKind::Output, + MixingKind::State, + ); + let honest = [ + value(input, 0), + value(input, 1), + value(stored, 0), + value(output, 0), + value(state, 0), + ]; + canonical::check_mixing(&honest).unwrap(); + canonical::check_mixing(&[]).unwrap(); + // a kind may be absent + canonical::check_mixing(&[value(stored, 0), value(stored, 1)]).unwrap(); + for bad in [ + vec![value(input, 1)], + vec![value(input, 0), value(input, 0)], + vec![value(input, 0), value(input, 2)], + vec![value(stored, 0), value(input, 0)], + vec![value(output, 0), value(state, 1)], + ] { + assert!(canonical::check_mixing(&bad).is_err(), "{bad:?}"); + } +} + +#[test] +fn a_list_in_the_wrong_stage_or_with_extras_is_refused() { + // anchors belong to the stage holding layer 0, the head to the last, + // and an entry leaf to every stage but the first + let message = fault(|opening| { + let anchors = opening.stages[0].anchors.clone(); + opening.stages[1].anchors = anchors; + }); + assert!(message.contains("the input of layer 0"), "{message}"); + fault(|opening| { + let head = opening.stages[1].head.clone(); + opening.stages[0].head = head; + }); + fault(|opening| { + let entry = opening.stages[1].entry.clone(); + opening.stages[0].entry = entry; + }); + // twice, missing, or at a position the challenge did not pick + fault(|opening| { + let copy = opening.stages[0].anchors[0].clone(); + opening.stages[0].anchors.insert(0, copy); + }); + fault(|opening| { + opening.stages[0].anchors.pop(); + }); + fault(|opening| { + let copy = opening.stages[1].head[0].clone(); + opening.stages[1].head.push(copy); + }); + fault(|opening| opening.stages[1].head.clear()); + fault(|opening| { + let copy = opening.stages[1].exit[0].clone(); + opening.stages[1].exit.push(copy); + }); + fault(|opening| { + opening.stages[0].exit.remove(0); + }); + fault(|opening| opening.stages[1].entry.swap(0, 1)); +} + +#[test] +fn partials_and_regions_are_opened_only_for_attention_picks() { + use crate::attention::opening::AttentionPartials; + let turn = Turn::new(); + let mut challenge = challenged(&turn); + challenge.attention = vec![challenge_pick(1, 3)]; + let honest = turn.open(&challenge); + let partials = |layer, position| { + AttentionPartials::new(&challenge_pick(layer, position), 0, &[0.0, 1.0, 2.0]) + }; + let verify = |change: &dyn Fn(&mut Opening)| { + let mut opening = honest.clone(); + change(&mut opening); + verify_paths(&turn.receipt, &challenge, &opening).map(|_| ()) + }; + // partials are no leaf: the pick's own are accepted here, and the + // attention check judges them + verify(&|opening| opening.stages[1].attention = vec![partials(1, 3)]).unwrap(); + let refused: [&dyn Fn(&mut Opening); 5] = [ + // not an attention pick + &|opening| opening.stages[1].attention = vec![partials(1, 0)], + // the pick's, on a stage that does not hold its layer + &|opening| opening.stages[0].attention = vec![partials(1, 3)], + // twice + &|opening| opening.stages[1].attention = vec![partials(1, 3), partials(1, 3)], + // a region for a position that is no attention pick + &|opening| opening.stages[1].recurrent = vec![region(1, 0)], + // two regions + &|opening| opening.stages[1].recurrent = vec![region(1, 3), region(1, 3)], + ]; + for (i, change) in refused.iter().enumerate() { + let error = verify(change).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "change {i}: {error:#}"); + } + // the pick's region is checked against the tree like any leaf + let error = verify(&|opening| opening.stages[1].recurrent = vec![region(1, 3)]).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} + +fn region(layer: u32, position: u32) -> crate::wire::RecurrentOpening { + crate::wire::RecurrentOpening { + position, + layer, + start: position, + end: position + 1, + leaves: Vec::new(), + } +} + +#[test] +fn every_opened_leaf_is_checked_against_its_root() { + let other = crate::wire::encode_f32(&[1.0, 2.0, 3.0, 4.0]); + let changes: Vec> = vec![ + Box::new(|o| o.stages[0].layers[0].leaves[1].residual_in = other.clone()), + Box::new(|o| o.stages[1].layers[0].leaves[0].residual_out = Some(other.clone())), + Box::new(|o| { + let bytes = [0u8; 8]; + o.stages[1].layers[0].leaves[0].mixing[1] = + TensorOpening::new(MixingKind::Stored, 0, Some((1, &bytes))); + }), + Box::new(|o| o.stages[0].anchors[2].residual = other.clone()), + Box::new(|o| o.stages[1].head[1].residual = other.clone()), + // the leaf leaving the final stage, which no later stage vouches for + Box::new(|o| o.stages[1].exit[0].leaf = hex::encode([3u8; 32])), + Box::new(|o| { + let leaf = hex::encode([3u8; 32]); + o.stages[0].exit[1].leaf = leaf.clone(); + o.stages[1].entry[1].leaf = leaf; + }), + Box::new(|o| o.stages[0].layers[0].leaves[0].mixing_path.clear()), + ]; + for (i, change) in changes.into_iter().enumerate() { + let message = fault(change); + assert!(!message.is_empty(), "change {i}"); + } +} + +#[test] +fn a_stored_row_of_a_type_the_receipt_does_not_name_is_refused() { + let message = fault(|opening| { + let row = &mut opening.stages[0].layers[0].leaves[0].mixing[1]; + row.ggml_type = 39; + }); + assert!(message.contains("type39"), "{message}"); +} + +#[test] +fn a_challenge_for_another_receipt_blames_nobody() { + let turn = Turn::new(); + let mut challenge = challenged(&turn); + let opening = turn.open(&challenge); + challenge.receipt_id = "another".into(); + let error = verify_paths(&turn.receipt, &challenge, &opening).unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} + +#[test] +fn a_cached_prefix_is_committed_exactly_when_the_turn_continues_one() { + use crate::wire::PrefixCommitment; + let fresh = Turn::new().receipt; + verify_shape(&fresh, LAYERS).unwrap(); + let continued = Turn::starting_at(40).receipt; + verify_shape(&continued, LAYERS).unwrap(); + let prefix = |positions| { + Some(PrefixCommitment { + root: hex::encode([7u8; 32]), + positions, + tokens: None, + }) + }; + let mut claimed = fresh.clone(); + claimed.stages[1].prefix = prefix(40); + let mut uncommitted = continued.clone(); + uncommitted.stages[0].prefix = None; + let mut shorter = continued.clone(); + shorter.stages[1].prefix = prefix(39); + // the stage that holds layer 0 commits the prefix's tokens, alone + let mut no_tokens = continued.clone(); + no_tokens.stages[0].prefix.as_mut().unwrap().tokens = None; + let mut extra_tokens = continued.clone(); + extra_tokens.stages[1].prefix.as_mut().unwrap().tokens = Some(hex::encode([1u8; 32])); + // a stage that keeps a recurrent state never commits a cached prefix + let mut recurrent = continued.clone(); + recurrent.stages[1].recurrent_state = Some(hex::encode([2u8; 32])); + let mut fresh_recurrent = fresh.clone(); + fresh_recurrent.stages[1].recurrent_state = Some(hex::encode([2u8; 32])); + verify_shape(&fresh_recurrent, LAYERS).unwrap(); + for receipt in [ + claimed, + uncommitted, + shorter, + no_tokens, + extra_tokens, + recurrent, + ] { + let error = verify_shape(&receipt, LAYERS).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + assert!(format!("{error:#}").contains("cached prefix"), "{error:#}"); + } +} + +#[test] +fn a_receipt_past_any_sequence_is_refused() { + // positions are i32 in the runtime: one past that would stop every + // check with an error instead of a verdict + let mut receipt = Turn::new().receipt; + let span = receipt.position_end - receipt.position_start; + receipt.position_start = u32::MAX - span; + receipt.position_end = u32::MAX; + receipt.generation_start = receipt.position_start + 1; + let error = verify_shape(&receipt, LAYERS).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + // another version is not a defect: this verifier cannot read it + let mut other = Turn::new().receipt; + other.version += 1; + let error = verify_shape(&other, LAYERS).unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} + +#[test] +fn a_turn_whose_first_sampled_token_comes_from_its_cached_prefix_is_refused() { + // the token sampled from the last prompt position would be in no + // opening a client can check + let mut receipt = Turn::starting_at(40).receipt; + assert!(receipt.generation_start > receipt.position_start); + receipt.generation_start = receipt.position_start; + let error = verify_shape(&receipt, LAYERS).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + assert!(format!("{error:#}").contains("first token"), "{error:#}"); +} diff --git a/crates/skippy-receipts/src/binding/verified.rs b/crates/skippy-receipts/src/binding/verified.rs new file mode 100644 index 00000000..6722e696 --- /dev/null +++ b/crates/skippy-receipts/src/binding/verified.rs @@ -0,0 +1,119 @@ +//! An opening whose form and Merkle paths were checked. + +use crate::attention::opening::{AttentionPartials, AttentionPick}; +use crate::wire::{ + AnchorOpening, Challenge, HeadOpening, LayerOpening, LeafOpening, Opening, Receipt, + RecurrentOpening, StageCommitment, StageOpening, +}; + +/// An opening that [`super::verify_paths`] accepted for a receipt and a +/// challenge. Only that function makes one. +/// +/// The opening is canonical, so it holds nothing but what the challenge +/// asks, and every leaf in it hashes to its stage root. A lookup here +/// therefore finds the one entry the checks ran on. What the node +/// recomputed by replay and no leaf commits (the matmuls, selections, +/// logits and attention partials) is here too; the other checks judge +/// those against the committed values. +#[derive(Clone, Copy, Debug)] +pub struct VerifiedOpening<'a> { + receipt: &'a Receipt, + challenge: &'a Challenge, + opening: &'a Opening, +} + +impl<'a> VerifiedOpening<'a> { + pub(super) fn new( + receipt: &'a Receipt, + challenge: &'a Challenge, + opening: &'a Opening, + ) -> Self { + Self { + receipt, + challenge, + opening, + } + } + + pub fn receipt(&self) -> &'a Receipt { + self.receipt + } + + pub fn challenge(&self) -> &'a Challenge { + self.challenge + } + + /// The whole opening. + pub fn opening(&self) -> &'a Opening { + self.opening + } + + /// Each stage of the receipt with what it opened, in order. + pub fn stages( + &self, + ) -> impl Iterator + use<'a> { + self.receipt.stages.iter().zip(&self.opening.stages) + } + + /// The stage holding `layer`, with what it opened. + fn stage_of(&self, layer: u32) -> Option<(&'a StageCommitment, &'a StageOpening)> { + self.stages() + .find(|(stage, _)| (stage.layer_start..stage.layer_end).contains(&layer)) + } + + /// The opening of a picked layer, with the backend of its stage. + pub fn layer(&self, layer: u32) -> Option<(&'a LayerOpening, &'a str)> { + let (stage, opened) = self.stage_of(layer)?; + let layer = opened.layers.iter().find(|l| l.layer == layer)?; + Some((layer, stage.backend.as_str())) + } + + /// One picked position of a picked layer. + pub fn leaf(&self, layer: u32, position: u32) -> Option<&'a LeafOpening> { + let (layer, _) = self.layer(layer)?; + layer.leaves.iter().find(|leaf| leaf.position == position) + } + + /// The tokens of the turn's cached prefix, from position 0, as the + /// stage that holds layer 0 opened them: they hash to the digest the + /// receipt commits. Empty for a turn that starts at position 0. + pub fn prefix_tokens(&self) -> &'a [i32] { + self.opening + .stages + .first() + .map_or(&[], |stage| stage.prefix_tokens.as_slice()) + } + + /// The input of layer 0 at every picked position. + pub fn anchors(&self) -> &'a [AnchorOpening] { + self.opening + .stages + .first() + .map_or(&[], |stage| stage.anchors.as_slice()) + } + + /// The final stage's backend and the residual the output head reads at + /// every head position of the challenge. + pub fn head(&self) -> Option<(&'a str, &'a [HeadOpening])> { + let (stage, opened) = self.stages().last()?; + Some((stage.backend.as_str(), opened.head.as_slice())) + } + + /// The partials the node opened for an attention pick, if it opened + /// any: a stage opens none in a layer without attention. + pub fn partials(&self, pick: &AttentionPick) -> Option<&'a AttentionPartials> { + let (_, opened) = self.stage_of(pick.layer)?; + opened + .attention + .iter() + .find(|a| a.position == pick.position && a.layer == pick.layer) + } + + /// The recurrent region `stage` opened, if it opened one. + pub fn region(&self, stage: &StageCommitment) -> Option<&'a RecurrentOpening> { + let (_, opened) = self + .stages() + .find(|(s, _)| s.stage_index == stage.stage_index)?; + opened.recurrent.first() + } +} diff --git a/crates/skippy-receipts/src/cache_types.rs b/crates/skippy-receipts/src/cache_types.rs new file mode 100644 index 00000000..940007e5 --- /dev/null +++ b/crates/skippy-receipts/src/cache_types.rs @@ -0,0 +1,160 @@ +//! The types of stored KV rows: the ones a row can be decoded in, and the +//! ones an audit covers. +//! +//! A stored row arrives from the node with a ggml type id. A row decodes in +//! the KV cache types a stage can serve with, and in f32 ([`DECODED`]). An +//! id outside that list is never decoded: the runtime may not know the type +//! at all, or may read more bytes for it than the node sent. +//! +//! An audit covers fewer types ([`AUDITED`]): f32 and f16. A quantized +//! cache (q8_0, q4_0) is not covered. Its rows differ from what the +//! attention of a prompt ubatch read by more than the loose attention check +//! allows: on CUDA, honest q8_0 turns were up to 5.5 times past the limit +//! (`docs/design/RECEIPTS_MEASUREMENTS.md`). So a stage with a +//! quantized cache issues no receipt, a client does not audit a receipt +//! that names one, and the auditor builds its own layer with an audited +//! type only. +//! +//! A node decodes its own cache rows here too, when it computes attention +//! partials ([`crate::attention`]), so both sides read a row the same way. + +use anyhow::Result; + +use crate::dequant::dequantize_row; +use crate::ggml_types::{GGML_F16, GGML_F32, GGML_Q4_0, GGML_Q8_0, type_layout, type_name}; +use crate::node_fault::{BlameNode, ensure_node}; + +/// The ggml types a stored row can be decoded in. +pub(crate) const DECODED: [u32; 4] = [GGML_F32, GGML_F16, GGML_Q4_0, GGML_Q8_0]; + +/// The ggml types of the stored rows an audit covers: a cache that is not +/// quantized. +pub(crate) const AUDITED: [u32; 2] = [GGML_F32, GGML_F16]; + +/// The type `ggml_type` names, if a stored row can be decoded in it. +pub fn decoded(ggml_type: i32) -> Option { + u32::try_from(ggml_type) + .ok() + .filter(|t| DECODED.contains(t)) +} + +/// The type `ggml_type` names, if an audit covers stored rows of it. +pub fn audited(ggml_type: i32) -> Option { + u32::try_from(ggml_type) + .ok() + .filter(|t| AUDITED.contains(t)) +} + +/// Whether a receipt's cache type name is a type an audit covers. +pub(crate) fn audited_name(name: &str) -> bool { + AUDITED.iter().any(|&t| type_name(t) == name) +} + +/// How a receipt names the type `ggml_type`. An id that is no type has a +/// name no receipt uses. +pub fn name(ggml_type: i32) -> String { + u32::try_from(ggml_type).map_or_else(|_| format!("type{ggml_type}"), type_name) +} + +/// The bytes of a row of `values` values in the type `ggml_type`; `None` when the type holds no whole row of that length. +pub fn row_bytes(ggml_type: u32, values: usize) -> Option { + let (block, bytes) = type_layout(ggml_type)?; + let (block, bytes) = (usize::try_from(block).ok()?, usize::try_from(bytes).ok()?); + values + .is_multiple_of(block) + .then(|| (values / block).checked_mul(bytes)) + .flatten() +} + +/// The values a stored row of `ggml_type` holds, decoded. Fails, as the +/// node's fault, for a type outside [`DECODED`], a row that is not whole +/// blocks of the type, or a value that is not a number. +pub(crate) fn decode_row(ggml_type: i32, bytes: &[u8]) -> Result> { + let Some(ggml_type) = decoded(ggml_type) else { + crate::node_fault::node_fault!( + "a stored row is of ggml type {ggml_type}, which the auditor does not decode" + ); + }; + let name = type_name(ggml_type); + let (block, block_bytes) = type_layout(ggml_type).unwrap_or((1, 4)); + let (block, block_bytes) = (block as usize, block_bytes as usize); + ensure_node!( + !bytes.is_empty() && bytes.len().is_multiple_of(block_bytes), + "a stored {name} row of {} bytes is not whole blocks of {block_bytes}", + bytes.len() + ); + let values = bytes.len() / block_bytes * block; + let row = dequantize_row(ggml_type, bytes, values).or_node_fault()?; + ensure_node!( + row.iter().all(|v| v.is_finite()), + "a stored {name} row holds a value that is not a number" + ); + Ok(row) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::node_fault::NodeFault; + + #[test] + fn a_row_decodes_only_in_the_cache_types_a_stage_serves_with() { + assert_eq!(decoded(1), Some(GGML_F16)); + assert_eq!(decoded(8), Some(GGML_Q8_0)); + // q4_1 is a ggml type no stage stores rows in; 4 and 39 are no types + for unknown in [3, 4, 39, -1, i32::MAX] { + assert_eq!(decoded(unknown), None, "{unknown}"); + } + assert_eq!(name(1), "f16"); + assert_eq!(name(-3), "type-3"); + } + + #[test] + fn an_audit_covers_no_quantized_cache() { + assert_eq!(audited(0), Some(GGML_F32)); + assert_eq!(audited(1), Some(GGML_F16)); + // a row decodes in q4_0 and q8_0, and no audit covers them + for quantized in [GGML_Q4_0, GGML_Q8_0] { + assert_eq!(decoded(quantized as i32), Some(quantized)); + assert_eq!(audited(quantized as i32), None, "{quantized}"); + } + for unknown in [3, 39, -1, i32::MAX] { + assert_eq!(audited(unknown), None, "{unknown}"); + } + assert!(audited_name("f16") && audited_name("f32")); + for name in ["q8_0", "q4_0", "q4_1", "type39", ""] { + assert!(!audited_name(name), "{name}"); + } + } + + #[test] + fn a_row_has_the_bytes_its_type_packs_its_values_into() { + assert_eq!(row_bytes(GGML_F32, 6), Some(24)); + assert_eq!(row_bytes(GGML_F16, 6), Some(12)); + assert_eq!(row_bytes(GGML_Q8_0, 64), Some(68)); + // q8_0 packs 32 values to a block + assert_eq!(row_bytes(GGML_Q8_0, 48), None); + assert_eq!(row_bytes(77, 4), None); + } + + #[test] + fn a_stored_row_decodes_only_when_whole_and_finite() { + let half = |v: f32| half::f16::from_f32(v).to_le_bytes(); + let row: Vec = [1.5f32, -2.0].into_iter().flat_map(half).collect(); + assert_eq!(decode_row(1, &row).unwrap(), vec![1.5, -2.0]); + let faults = [ + decode_row(1, &row[..3]), + decode_row(1, &[]), + decode_row(39, &row), + decode_row(1, &half(f32::NAN)), + decode_row(1, &half(f32::INFINITY)), + decode_row(0, &f32::NAN.to_le_bytes()), + // a q8_0 block needs 34 bytes + decode_row(8, &[0; 33]), + ]; + for fault in faults { + let error = fault.unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + } + } +} diff --git a/crates/skippy-receipts/src/challenge.rs b/crates/skippy-receipts/src/challenge.rs new file mode 100644 index 00000000..bfff902d --- /dev/null +++ b/crates/skippy-receipts/src/challenge.rs @@ -0,0 +1,516 @@ +//! The client's random challenge: [`LAYERS_PER_CHALLENGE`] layers of the +//! claimed model, each chosen with probability proportional to its weight +//! bytes, and [`POSITIONS_PER_LAYER`] positions in each. +//! +//! It also picks [`HEAD_POSITIONS`] of the positions the turn sampled a +//! token from, whose token the client checks against the output head. +//! And it picks [`ATTENTION_POSITIONS_PER_LAYER`] of each layer's positions, +//! with a head each, whose attention the client checks +//! ([`crate::attention`]). +//! +//! When the turn continued a cached prefix, it picks [`PREFIX_POSITIONS`] +//! positions of the prefix as well, the same in every layer. The node opens +//! them like the turn's own, so a prefix the node did not compute with the +//! claimed model is caught like a turn it did not. +//! +//! Every draw comes from the VRF output of the receipt's turn root under +//! the client's key ([`crate::vrf`]), through a [`DrawStream`], so anyone +//! holding the proof can recompute the challenge and see that the client +//! did not pick it. +//! +//! Spreading the positions over several layers matters: a node that breaks +//! the chain from one layer to the next at a single layer is caught only +//! when that layer is picked, so four layers catch it about four times as +//! often as one. Half of each layer's positions are decode positions when +//! the turn generated any, because a node that cheats only on the tokens it +//! shows would otherwise hide behind a long prompt. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use anyhow::{Result, bail}; + +use crate::attention::opening::AttentionPick; +use crate::draw::DrawStream; +use crate::wire::{Challenge, Pick, Receipt}; + +pub const LAYERS_PER_CHALLENGE: usize = 4; +pub const POSITIONS_PER_LAYER: usize = 4; +pub const HEAD_POSITIONS: usize = 4; +/// Positions of each picked layer whose attention the client checks. +pub const ATTENTION_POSITIONS_PER_LAYER: usize = 2; +/// Positions of the turn's cached prefix a challenge picks, in every picked +/// layer. A node replays one recorded ubatch for each, so this bounds the +/// work a cached turn's opening adds. +pub const PREFIX_POSITIONS: usize = 2; + +/// Label of the challenge draws. +const CHALLENGE_LABEL: &str = "challenge"; +/// Label of the head positions. +const HEAD_LABEL: &str = "head"; +/// Label of the attention picks. +const ATTENTION_LABEL: &str = "attention"; +/// Label of the prefix positions. +const PREFIX_LABEL: &str = "prefix"; +/// Label of the audit-rate decision. +const AUDIT_LABEL: &str = "audit"; + +/// Whether the client audits the turn whose VRF output is `seed`, at `rate`. +pub fn audits(seed: &[u8], rate: f64) -> bool { + DrawStream::new(seed, AUDIT_LABEL).unit() < rate +} + +/// Draws a challenge for `receipt` from `seed`, the VRF output of its turn +/// root. `layer_bytes` comes from the claimed GGUF; layers it does not +/// list, or lists with no bytes, are never picked. +pub fn draw(receipt: &Receipt, layer_bytes: &BTreeMap, seed: &[u8]) -> Result { + let mut stream = DrawStream::new(seed, CHALLENGE_LABEL); + let mut candidates: Vec<(u32, u64)> = layer_bytes + .iter() + .filter(|(_, bytes)| **bytes > 0) + .map(|(layer, bytes)| (*layer, *bytes)) + .collect(); + if candidates.is_empty() { + bail!("the claimed model has no weight bytes"); + } + if receipt.position_end <= receipt.position_start { + bail!("the receipt covers no positions"); + } + let mut layers = BTreeSet::new(); + while layers.len() < LAYERS_PER_CHALLENGE && !candidates.is_empty() { + let total: u64 = candidates.iter().map(|(_, b)| b).sum(); + let mut ticket = stream.below(total); + let index = candidates + .iter() + .position(|(_, bytes)| { + let hit = ticket < *bytes; + ticket = ticket.saturating_sub(*bytes); + hit + }) + .expect("a ticket below the total"); + layers.insert(candidates.swap_remove(index).0); + } + let prompt = receipt.position_start..receipt.generation_start; + let decode = receipt.generation_start..receipt.position_end; + let prefix = draw_prefix(receipt.position_start, seed); + let picks: Vec = layers + .into_iter() + .map(|layer| Pick { + layer, + // the prefix lies below the turn, so the positions stay sorted + positions: prefix + .iter() + .copied() + .chain(draw_positions(prompt.clone(), decode.clone(), &mut stream)) + .collect(), + }) + .collect(); + Ok(Challenge { + receipt_id: receipt.receipt_id.clone(), + attention: draw_attention(&picks, seed), + picks, + proof: None, + head: draw_head(receipt, seed), + }) +} + +/// Refuses a challenge that no draw makes: more layers, positions, head +/// positions or attention picks than [`draw`] picks, in another order, or +/// outside the receipt. A node checks this before it replays anything, so +/// the work of an opening is bounded whoever sends the challenge. +pub fn check_shape(challenge: &Challenge, receipt: &Receipt) -> Result<()> { + if challenge.receipt_id != receipt.receipt_id { + bail!("the challenge names another receipt"); + } + if challenge.picks.len() > LAYERS_PER_CHALLENGE { + bail!( + "the challenge picks {} layers; a draw picks at most {LAYERS_PER_CHALLENGE}", + challenge.picks.len() + ); + } + let increasing = |values: &[u32]| values.windows(2).all(|pair| pair[0] < pair[1]); + let layers: Vec = challenge.picks.iter().map(|p| p.layer).collect(); + if !increasing(&layers) { + bail!("the challenge's layers are not in increasing order"); + } + if let Some(pick) = challenge + .picks + .iter() + .find(|pick| pick.layer >= receipt.layer_count()) + { + bail!("layer {} is not in the receipt", pick.layer); + } + check_picked_positions( + &challenge.picks, + &(receipt.position_start..receipt.position_end), + )?; + // a head position is one the turn sampled a token from, so it is never + // a position of the prefix: a prefix holds what an earlier request fed + let outputs = receipt.output_positions(); + if challenge.head.len() > HEAD_POSITIONS + || !increasing(&challenge.head) + || !challenge.head.iter().all(|p| outputs.contains(p)) + { + bail!( + "the head positions are not at most {HEAD_POSITIONS} increasing positions the turn sampled from" + ); + } + let mut seen = BTreeSet::new(); + let mut per_layer: BTreeMap = BTreeMap::new(); + for pick in &challenge.attention { + let picked = challenge + .picks + .iter() + .any(|p| p.layer == pick.layer && p.positions.contains(&pick.position)); + if !picked || !seen.insert((pick.layer, pick.position)) { + bail!( + "attention pick at position {} of layer {} is not one picked position, once", + pick.position, + pick.layer + ); + } + let count = per_layer.entry(pick.layer).or_default(); + *count += 1; + if *count > ATTENTION_POSITIONS_PER_LAYER { + bail!( + "layer {} has more than {ATTENTION_POSITIONS_PER_LAYER} attention picks", + pick.layer + ); + } + } + Ok(()) +} + +/// Refuses picks whose positions no draw makes for a turn at positions +/// `turn`: in every pick, 1 to [`POSITIONS_PER_LAYER`] positions of the +/// turn, after at most [`PREFIX_POSITIONS`] positions of its prefix, the +/// same in every pick, all in increasing order. Every stage checks this, so +/// a stage opens at most [`PREFIX_POSITIONS`] positions of a prefix for one +/// challenge. +pub(crate) fn check_picked_positions(picks: &[Pick], turn: &Range) -> Result<()> { + let mut prefix: Option<&[u32]> = None; + for pick in picks { + let increasing = pick.positions.windows(2).all(|pair| pair[0] < pair[1]); + if !increasing || pick.positions.last().is_some_and(|last| *last >= turn.end) { + bail!( + "the positions of layer {} are not increasing positions of the turn or its prefix", + pick.layer + ); + } + let (below, own) = pick + .positions + .split_at(pick.positions.partition_point(|p| *p < turn.start)); + if own.is_empty() || own.len() > POSITIONS_PER_LAYER { + bail!( + "layer {} picks {} positions of the turn; a draw picks 1 to {POSITIONS_PER_LAYER}", + pick.layer, + own.len() + ); + } + if below.len() > PREFIX_POSITIONS { + bail!( + "layer {} picks {} positions of the prefix; a draw picks at most {PREFIX_POSITIONS}", + pick.layer, + below.len() + ); + } + if prefix.is_some_and(|picked| picked != below) { + bail!("the challenge's layers pick different positions of the prefix"); + } + prefix = Some(below); + } + Ok(()) +} + +/// [`PREFIX_POSITIONS`] distinct positions of a prefix of `length` +/// positions, sorted, or every position of a shorter one. +fn draw_prefix(length: u32, seed: &[u8]) -> Vec { + let mut stream = DrawStream::new(seed, PREFIX_LABEL); + let mut positions = BTreeSet::new(); + sample( + &(0..length), + PREFIX_POSITIONS.min(length as usize), + &mut stream, + &mut positions, + ); + positions.into_iter().collect() +} + +/// [`ATTENTION_POSITIONS_PER_LAYER`] of each pick's positions, with a +/// head draw each. A challenge whose picks are changed draws them again. +pub fn draw_attention(picks: &[Pick], seed: &[u8]) -> Vec { + let mut stream = DrawStream::new(seed, ATTENTION_LABEL); + let mut attention = Vec::new(); + for pick in picks { + let mut positions = pick.positions.clone(); + let count = ATTENTION_POSITIONS_PER_LAYER.min(positions.len()); + for _ in 0..count { + let index = stream.below(positions.len() as u64) as usize; + let position = positions.swap_remove(index); + attention.push(AttentionPick { + position, + layer: pick.layer, + head_draw: stream.below(1 << 32) as u32, + }); + } + } + attention +} + +/// [`HEAD_POSITIONS`] distinct output positions, sorted. +fn draw_head(receipt: &Receipt, seed: &[u8]) -> Vec { + let outputs = receipt.output_positions(); + let mut stream = DrawStream::new(seed, HEAD_LABEL); + let mut positions = BTreeSet::new(); + sample( + &outputs, + HEAD_POSITIONS.min(outputs.len()), + &mut stream, + &mut positions, + ); + positions.into_iter().collect() +} + +/// [`POSITIONS_PER_LAYER`] distinct positions, half from each span when both +/// have enough, sorted. +fn draw_positions(prompt: Range, decode: Range, stream: &mut DrawStream) -> Vec { + let wanted = POSITIONS_PER_LAYER.min(prompt.len() + decode.len()); + let from_decode = (wanted / 2) + .max(wanted.saturating_sub(prompt.len())) + .min(decode.len()); + let mut positions = BTreeSet::new(); + sample(&decode, from_decode, stream, &mut positions); + sample(&prompt, wanted - from_decode, stream, &mut positions); + positions.into_iter().collect() +} + +fn sample(span: &Range, count: usize, stream: &mut DrawStream, into: &mut BTreeSet) { + let target = into.len() + count; + while into.len() < target { + into.insert(stream.in_range(span.clone())); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire::{RECEIPT_VERSION, StageCommitment}; + + fn receipt(start: u32, generation: u32, end: u32) -> Receipt { + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: start, + position_end: end, + tokens: vec![0; (end - start) as usize], + generation_start: generation, + final_token: Some(1), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 8, + root: String::new(), + leaf_count: 0, + backend: String::new(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: None, + } + } + + fn bytes(layers: u32) -> BTreeMap { + (0..layers).map(|l| (l, 1)).collect() + } + + #[test] + fn picks_distinct_layers_with_sorted_positions_in_range() { + for seed in 0..50u8 { + let c = draw(&receipt(10, 30, 40), &bytes(8), &[seed]).unwrap(); + assert_eq!(c.picks.len(), LAYERS_PER_CHALLENGE); + assert!(c.picks.windows(2).all(|w| w[0].layer < w[1].layer)); + for pick in &c.picks { + // two positions of the prefix, then four of the turn + assert_eq!(pick.positions.len(), PREFIX_POSITIONS + POSITIONS_PER_LAYER); + assert!(pick.positions.windows(2).all(|w| w[0] < w[1])); + let (prefix, turn) = pick.positions.split_at(PREFIX_POSITIONS); + assert!(prefix.iter().all(|p| (0..10).contains(p))); + assert!(turn.iter().all(|p| (10..40).contains(p))); + assert_eq!(prefix, &c.picks[0].positions[..PREFIX_POSITIONS]); + } + } + } + + #[test] + fn a_prefix_is_picked_exactly_when_the_turn_continues_one() { + let prefix_of = |start: u32| { + let r = receipt(start, start + 2, start + 4); + let c = draw(&r, &bytes(8), b"seed").unwrap(); + check_shape(&c, &r).unwrap(); + c.prefix_positions(start) + }; + assert!(prefix_of(0).is_empty()); + // a prefix of one position is picked whole + assert_eq!(prefix_of(1), vec![0]); + assert_eq!(prefix_of(2), vec![0, 1]); + let large = prefix_of(30_000); + assert_eq!(large.len(), PREFIX_POSITIONS); + assert!(large.iter().all(|p| *p < 30_000)); + // the positions come from a stream of their own: the layers and the + // turn's positions are the ones a turn without a prefix would get + let (with, without) = (receipt(5, 7, 9), receipt(0, 2, 4)); + let with = draw(&with, &bytes(8), b"seed").unwrap(); + let without = draw(&without, &bytes(8), b"seed").unwrap(); + for (a, b) in with.picks.iter().zip(&without.picks) { + assert_eq!(a.layer, b.layer); + let turn: Vec = a.positions[PREFIX_POSITIONS..] + .iter() + .map(|p| p - 5) + .collect(); + assert_eq!(turn, b.positions); + } + } + + #[test] + fn every_draw_fits_the_shape_a_node_admits() { + for seed in 0..50u8 { + for (start, generation, end) in [(10, 30, 40), (0, 3000, 3004), (3, 5, 6), (0, 1, 2)] { + let r = receipt(start, generation, end); + let c = draw(&r, &bytes(8), &[seed]).unwrap(); + check_shape(&c, &r).unwrap(); + } + } + } + + #[test] + fn a_challenge_no_draw_makes_is_refused() { + let r = receipt(10, 30, 40); + let drawn = draw(&r, &bytes(8), b"seed").unwrap(); + type Change = Box; + let changes: Vec = vec![ + Box::new(|c| c.receipt_id = "other".into()), + // every layer at every position + Box::new(|c| { + c.picks = (0..8) + .map(|layer| Pick { + layer, + positions: (10..40).collect(), + }) + .collect(); + }), + Box::new(|c| c.picks[0].positions = (10..15).collect()), + Box::new(|c| c.picks[0].positions = Vec::new()), + Box::new(|c| c.picks[0].positions = vec![12, 11]), + Box::new(|c| c.picks[0].positions = vec![11, 11]), + Box::new(|c| c.picks[0].positions = vec![9]), + Box::new(|c| c.picks[0].positions = vec![40]), + // more positions of the prefix than a draw picks + Box::new(|c| { + for pick in &mut c.picks { + let turn = pick.positions.split_off(PREFIX_POSITIONS); + pick.positions = (0..=PREFIX_POSITIONS as u32).chain(turn).collect(); + } + }), + // other positions of the prefix in one layer than in the rest + Box::new(|c| { + let other = (0..10).find(|p| !c.picks[0].positions.contains(p)).unwrap(); + c.picks[0].positions[0] = other; + c.picks[0].positions.sort_unstable(); + }), + // a position of the prefix sampled no token + Box::new(|c| c.head = vec![c.picks[0].positions[0]]), + Box::new(|c| c.picks[0].layer = 8), + Box::new(|c| c.picks.swap(0, 1)), + Box::new(|c| c.picks[1].layer = c.picks[0].layer), + Box::new(|c| c.head = (29..40).collect()), + Box::new(|c| c.head = vec![12]), + Box::new(|c| c.head = vec![31, 30]), + Box::new(|c| c.attention[0].layer = 99), + Box::new(|c| c.attention[0].position = 40), + Box::new(|c| c.attention[1] = c.attention[0].clone()), + Box::new(|c| { + let layer = c.picks[0].layer; + c.attention = c.picks[0] + .positions + .iter() + .map(|&position| AttentionPick { + position, + layer, + head_draw: 0, + }) + .collect(); + }), + ]; + for (i, change) in changes.iter().enumerate() { + let mut c = drawn.clone(); + change(&mut c); + assert!(check_shape(&c, &r).is_err(), "change {i} was admitted"); + } + check_shape(&drawn, &r).unwrap(); + } + + #[test] + fn half_of_each_layers_positions_are_decode_positions() { + // 3000 prompt positions and 4 decode positions + for seed in 0..50u8 { + let c = draw(&receipt(0, 3000, 3004), &bytes(8), &[seed]).unwrap(); + for pick in &c.picks { + let decode = pick.positions.iter().filter(|&&p| p >= 3000).count(); + assert_eq!(decode, POSITIONS_PER_LAYER / 2); + } + } + } + + #[test] + fn a_short_span_is_filled_from_the_other() { + let c = draw(&receipt(0, 1, 9), &bytes(8), b"seed").unwrap(); + for pick in &c.picks { + assert_eq!(pick.positions.len(), POSITIONS_PER_LAYER); + } + let c = draw(&receipt(3, 5, 6), &bytes(8), b"seed").unwrap(); + assert_eq!(c.picks[0].positions[PREFIX_POSITIONS..], [3, 4, 5]); + } + + #[test] + fn head_positions_are_output_positions() { + for seed in 0..50u8 { + let r = receipt(10, 30, 40); + let c = draw(&r, &bytes(8), &[seed]).unwrap(); + assert_eq!(c.head.len(), HEAD_POSITIONS); + assert!(c.head.windows(2).all(|w| w[0] < w[1])); + assert!(c.head.iter().all(|p| r.output_positions().contains(p))); + } + // two outputs: the last prompt position and the one that sampled the final token + let c = draw(&receipt(0, 5, 6), &bytes(8), b"seed").unwrap(); + assert_eq!(c.head, vec![4, 5]); + } + + #[test] + fn the_seed_decides_the_challenge() { + let r = receipt(0, 100, 200); + let a = draw(&r, &bytes(36), b"one").unwrap(); + assert_eq!(a, draw(&r, &bytes(36), b"one").unwrap()); + assert_ne!(a, draw(&r, &bytes(36), b"two").unwrap()); + } + + #[test] + fn the_audit_rate_holds_over_many_seeds() { + let audited = (0..10_000u32) + .filter(|seed| audits(&seed.to_le_bytes(), 0.1)) + .count(); + assert!((800..1200).contains(&audited), "{audited}"); + assert!(!audits(b"x", 0.0)); + assert!(audits(b"x", 1.0)); + } + + #[test] + fn layers_without_bytes_are_never_picked() { + let only = BTreeMap::from([(2, 5), (3, 0)]); + let c = draw(&receipt(0, 2, 4), &only, b"seed").unwrap(); + assert_eq!(c.picks.len(), 1); + assert_eq!(c.picks[0].layer, 2); + } +} diff --git a/crates/skippy-receipts/src/claimed_reads.rs b/crates/skippy-receipts/src/claimed_reads.rs new file mode 100644 index 00000000..1f105537 --- /dev/null +++ b/crates/skippy-receipts/src/claimed_reads.rs @@ -0,0 +1,107 @@ +//! The bytes of the claimed GGUF the glue check of an opening reads, so a +//! client that holds a sparse copy fetches them before it loads a layer. +//! +//! A layer loads whole, so the copy must hold every tensor the evaluation +//! reads before the load: the loader copies the tensors and does not see +//! bytes fetched later. The glue evaluation does not read the weights of +//! the matmuls the opening holds; their opened outputs replace them. The +//! input of layer 0 reads one row of the token embedding per anchor. +//! +//! A layer also reads tensors that are not its own: frequency factors of +//! its position encoding (`rope_freqs.weight`), shared norms and +//! projections, whatever its graph names. Which ones is the native +//! planner's to say, and this module has only the header, so it takes every +//! tensor outside the layers but the two large matrices, the token +//! embedding and the output head, which are read by row. A hole where a +//! layer reads one of them is zeros to the loader, and would fail an honest +//! node. One that is too large to fetch whole +//! ([`WHOLE_TENSOR_LIMIT`]) cannot be audited from a sparse copy. +//! +//! The row check and the head check read their rows through the +//! [`WeightFile`] and fetch them themselves. Everything here and there +//! counts against the file's fetch budget. + +use std::collections::BTreeSet; + +use anyhow::Result; + +use crate::weights::limits::{WHOLE_TENSOR_LIMIT, refuse}; +use crate::weights::{TensorInfo, WeightFile}; +use crate::wire::Opening; + +/// The token embedding, which the input of layer 0 reads a row of per token. +pub(crate) const TOKEN_EMBEDDING: &str = "token_embd.weight"; +/// The output head, which the head check reads by row. +pub(crate) const OUTPUT_HEAD: &str = "output.weight"; + +/// The ranges, `(offset, len)`, that loading `layers` and checking the +/// anchors of `opening` read. +pub fn glue_ranges( + weights: &WeightFile, + opening: &Opening, + layers: &[u32], +) -> Result> { + let opened: BTreeSet<&str> = opening + .stages + .iter() + .flat_map(|s| &s.layers) + .flat_map(|l| &l.leaves) + .flat_map(|leaf| &leaf.matrices) + .map(|m| m.weight.as_str()) + .collect(); + let mut layers: BTreeSet = layers.iter().copied().collect(); + let anchors: Vec = opening + .stages + .first() + .map(|s| s.anchors.iter().map(|a| a.token).collect()) + .unwrap_or_default(); + if !anchors.is_empty() { + layers.insert(0); + } + let mut ranges = Vec::new(); + for t in weights.tensors.values() { + let Some(layer) = t.layer() else { + ranges.extend(shared_range(weights, t)?); + continue; + }; + // a layer the opening has no matmuls of reads none of its matrices + let skipped = + opened.contains(t.name.as_str()) || (t.is_matrix() && !opened_layer(&opened, layer)); + if layers.contains(&layer) && !skipped { + ranges.push((t.offset, t.total_bytes()?)); + } + } + if weights.tensors.contains_key(TOKEN_EMBEDDING) { + for token in anchors { + ranges.push(weights.row_range(TOKEN_EMBEDDING, u64::try_from(token)?)?); + } + } + Ok(ranges) +} + +/// The range of a tensor outside the layers, which any layer may read: all +/// of it, but nothing of the two matrices read by row. A tensor too large +/// to fetch whole is refused when the copy does not hold it; a local file +/// holds every tensor. +fn shared_range(weights: &WeightFile, t: &TensorInfo) -> Result> { + if t.name == TOKEN_EMBEDDING || t.name == OUTPUT_HEAD { + return Ok(None); + } + let range = (t.offset, t.total_bytes()?); + if range.1 > WHOLE_TENSOR_LIMIT && weights.missing_bytes(&[range])? > 0 { + return refuse(format!( + "a layer may read {}, which is outside the layers and, at {} bytes, more than the {WHOLE_TENSOR_LIMIT} a sparse copy fetches whole; audit against a local copy of the model", + t.name, range.1 + )); + } + Ok(Some(range)) +} + +/// Whether the opening holds any matmul of `layer`. +fn opened_layer(opened: &BTreeSet<&str>, layer: u32) -> bool { + let prefix = format!("blk.{layer}."); + opened.iter().any(|name| name.starts_with(&prefix)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/claimed_reads/tests.rs b/crates/skippy-receipts/src/claimed_reads/tests.rs new file mode 100644 index 00000000..8bd0f924 --- /dev/null +++ b/crates/skippy-receipts/src/claimed_reads/tests.rs @@ -0,0 +1,146 @@ +use super::*; +use crate::ggml_types::GGML_F32; +use crate::weights::limits::CannotAudit; +use crate::weights::test_gguf; + +fn opening(json: serde_json::Value) -> Opening { + serde_json::from_value(json).unwrap() +} + +fn matrix(weight: &str) -> serde_json::Value { + serde_json::json!({"index": 0, "weight": weight, "input": "", "output": ""}) +} + +fn leaf(matrices: Vec) -> serde_json::Value { + serde_json::json!({ + "position": 3, "residual_in": "", "residual_out": null, + "residual_in_path": [], "mixing_path": [], "residual_out_path": [], + "mixing": [], "matrices": matrices, "selections": [], + }) +} + +/// An opening of layer 1 that holds its `attn_q` matmul and one anchor, of +/// token 2. +fn layer_one() -> Opening { + opening(serde_json::json!({ + "receipt_id": "r", + "stages": [{ + "stage_index": 0, + "layers": [{"layer": 1, "leaves": [leaf(vec![matrix("blk.1.attn_q.weight")])]}], + "anchors": [{"position": 3, "token": 2, "residual": "", "path": []}], + }], + })) +} + +#[test] +fn a_layer_reads_its_small_tensors_the_shared_ones_and_the_anchor_rows() { + let weights = test_gguf::open( + &[], + &[ + ("token_embd.weight", vec![2, 4], vec![0.0; 8]), + ("blk.0.attn_norm.weight", vec![2], vec![1.0; 2]), + ("blk.0.attn_q.weight", vec![2, 2], vec![0.0; 4]), + ("blk.1.attn_norm.weight", vec![2], vec![1.0; 2]), + ("blk.1.attn_q.weight", vec![2, 2], vec![0.0; 4]), + ("blk.1.attn_k.weight", vec![2, 2], vec![0.0; 4]), + ("blk.2.attn_norm.weight", vec![2], vec![1.0; 2]), + ("output_norm.weight", vec![2], vec![1.0; 2]), + ("rope_freqs.weight", vec![1], vec![1.0]), + ("per_layer_proj.weight", vec![2, 2], vec![0.0; 4]), + ("output.weight", vec![2, 4], vec![0.0; 8]), + ], + ); + let mut ranges = glue_ranges(&weights, &layer_one(), &[1]).unwrap(); + ranges.sort_unstable(); + let range = |name: &str| weights.tensor_range(name).unwrap(); + let mut expected = vec![ + range("blk.0.attn_norm.weight"), + range("blk.1.attn_norm.weight"), + // not opened, so the glue may read it + range("blk.1.attn_k.weight"), + // outside the layers: a layer's graph may name any of them, and a + // hole where it reads one would be zeros to the loader + range("output_norm.weight"), + range("rope_freqs.weight"), + range("per_layer_proj.weight"), + weights.row_range("token_embd.weight", 2).unwrap(), + ]; + expected.sort_unstable(); + assert_eq!(ranges, expected); +} + +/// A remote model, its header held, with the tensor `shared` outside the +/// layers. +fn remote_with(shared: (&str, Vec)) -> WeightFile { + let (header, data) = test_gguf::header( + &[], + &[ + ("token_embd.weight", vec![2, 4], GGML_F32), + ("blk.1.attn_norm.weight", vec![2], GGML_F32), + ("blk.1.attn_q.weight", vec![2, 2], GGML_F32), + (shared.0, shared.1, GGML_F32), + ], + ); + let size = header.len() as u64 + data; + WeightFile::open_with_budget( + Box::new(test_gguf::Remote::new(header, size)), + crate::weights::limits::AUDIT_FETCH_BUDGET, + ) + .unwrap() +} + +#[test] +fn a_shared_tensor_too_large_to_fetch_whole_is_not_audited_from_a_copy() { + // a float past the limit + let rows = WHOLE_TENSOR_LIMIT / 16 + 1; + let weights = remote_with(("per_layer_token_embd.weight", vec![4, rows])); + let error = glue_ranges(&weights, &layer_one(), &[1]).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!( + error.to_string().contains("per_layer_token_embd.weight"), + "{error}" + ); + // at the limit it is fetched + let weights = remote_with(("per_layer_proj.weight", vec![4, WHOLE_TENSOR_LIMIT / 16])); + let ranges = glue_ranges(&weights, &layer_one(), &[1]).unwrap(); + let shared = weights.tensor_range("per_layer_proj.weight").unwrap(); + assert_eq!(shared.1, WHOLE_TENSOR_LIMIT); + assert!(ranges.contains(&shared)); + // the two matrices read by row are never fetched whole, however large + let weights = remote_with(("output.weight", vec![4, rows])); + let ranges = glue_ranges(&weights, &layer_one(), &[1]).unwrap(); + assert!(!ranges.contains(&weights.tensor_range("output.weight").unwrap())); +} + +#[test] +fn the_tensors_a_layer_loads_count_against_the_budget() { + let weights = remote_with(("rope_freqs.weight", vec![64])); + let ranges = glue_ranges(&weights, &layer_one(), &[1]).unwrap(); + // the norm, the frequency factors and the anchor's row + let bytes: u64 = ranges.iter().map(|(_, len)| len).sum(); + assert_eq!(bytes, 8 + 256 + 8); + weights.set_fetch_budget(bytes - 1); + let error = weights.prefetch(&ranges).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + weights.set_fetch_budget(bytes); + weights.prefetch(&ranges).unwrap(); + assert_eq!(weights.fetched_bytes(), bytes); +} + +#[test] +fn a_tensor_of_a_type_without_a_size_is_an_error_not_a_hole() { + let mut weights = test_gguf::open( + &[], + &[ + ("blk.1.attn_norm.weight", vec![2], vec![1.0; 2]), + ("rope_freqs.weight", vec![1], vec![1.0]), + ], + ); + // a type id ggml removed: once sized zero, so never fetched + weights + .tensors + .get_mut("blk.1.attn_norm.weight") + .unwrap() + .ggml_type = 4; + assert!(glue_ranges(&weights, &layer_one(), &[1]).is_err()); +} diff --git a/crates/skippy-receipts/src/commitment.rs b/crates/skippy-receipts/src/commitment.rs new file mode 100644 index 00000000..f860e67c --- /dev/null +++ b/crates/skippy-receipts/src/commitment.rs @@ -0,0 +1,597 @@ +//! Leaf hashing and the BLAKE3 Merkle tree over a stage's turn. +//! +//! A stage holding layers `start..end` commits, for every position, to +//! `2 · (end - start) + 1` leaves in this order: +//! +//! `residual(start), mixing(start), residual(start + 1), ..., mixing(end - 1), residual(end)` +//! +//! A residual leaf holds the residual stream entering a layer (`residual(end)` +//! is the stage output). A mixing leaf holds the inputs, stored KV or state +//! rows, and outputs of the layer's token-mixing ops (see +//! [`crate::layer_tensors`]): a hash of the stored rows ([`stored_leaf`]) and +//! a hash of the other values ([`mixing_rest`]), so a stored row can be +//! opened without the others. Leaves are ordered by position, then by that +//! slot order. + +use anyhow::{Context, Result, anyhow, bail}; + +use crate::layer_tensors::TensorKind; + +const RESIDUAL_DOMAIN: &[u8] = b"skippy-receipt-residual-v1"; +const MIXING_DOMAIN: &[u8] = b"skippy-receipt-mixing-v2"; +const MIXING_REST_DOMAIN: &[u8] = b"skippy-receipt-mixing-rest-v1"; +const STORED_DOMAIN: &[u8] = b"skippy-receipt-stored-v1"; +const NODE_DOMAIN: &[u8] = b"skippy-receipt-node-v0"; +const RECURRENT_STATE_DOMAIN: &[u8] = b"skippy-receipt-recurrent-state-v1"; +const PREFIX_DOMAIN: &[u8] = b"skippy-receipt-prefix-v2"; +const POSITION_DOMAIN: &[u8] = b"skippy-receipt-position-v1"; +const PREFIX_TOKENS_DOMAIN: &[u8] = b"skippy-receipt-prefix-tokens-v1"; + +pub type Hash = [u8; 32]; + +/// Decodes `N` bytes from hex; `what` names the value in errors. +pub fn hex_array(text: &str, what: &str) -> Result<[u8; N]> { + let bytes = hex::decode(text).with_context(|| format!("decode {what} from hex"))?; + <[u8; N]>::try_from(bytes.as_slice()) + .map_err(|_| anyhow!("{what} has {} bytes, not {N}", bytes.len())) +} + +/// Leaves per position for a stage holding `layers` layers. +pub fn slots_per_position(layer_start: u32, layer_end: u32) -> u64 { + 2 * u64::from(layer_end - layer_start) + 1 +} + +/// Slot of the residual stream entering `layer` (`layer == layer_end` is the output). +pub(crate) fn residual_slot(layer: u32, layer_start: u32) -> u64 { + 2 * u64::from(layer - layer_start) +} + +/// Slot of the mixing leaf of `layer`. +pub(crate) fn mixing_slot(layer: u32, layer_start: u32) -> u64 { + residual_slot(layer, layer_start) + 1 +} + +/// Index of a leaf in a stage tree. +pub(crate) fn leaf_index(position: u32, slot: u64, position_start: u32, slots: u64) -> u64 { + u64::from(position - position_start) * slots + slot +} + +/// A committed value as a leaf binds it: its byte length and the BLAKE3 hash +/// of its bytes. A recorder can take the digest where the value is computed, +/// on the device, and copy 32 bytes instead of the value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ValueDigest { + pub len: u32, + pub digest: Hash, +} + +impl ValueDigest { + pub fn of(bytes: &[u8]) -> Self { + Self { + len: bytes.len() as u32, + digest: *blake3::hash(bytes).as_bytes(), + } + } + + fn hash_into(&self, hasher: &mut blake3::Hasher) { + hasher.update(&self.len.to_le_bytes()); + hasher.update(&self.digest); + } +} + +/// The residual leaf of `layer` at `position`, over little-endian f32 +/// bytes. `None` marks a row the layer did not produce: the final layer of +/// a final stage keeps only output rows. The residual entering layer 0 also +/// binds the position's token, so the auditor can recompute it. +pub(crate) fn residual_leaf( + position: u32, + layer: u32, + token: Option, + values: Option<&[u8]>, +) -> Hash { + residual_leaf_of(position, layer, token, values.map(ValueDigest::of)) +} + +/// [`residual_leaf`] from the digest of the values. +pub(crate) fn residual_leaf_of( + position: u32, + layer: u32, + token: Option, + value: Option, +) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(RESIDUAL_DOMAIN); + hasher.update(&position.to_le_bytes()); + hasher.update(&layer.to_le_bytes()); + match token { + Some(token) => { + hasher.update(&[1]); + hasher.update(&token.to_le_bytes()); + } + None => { + hasher.update(&[0]); + } + } + match value { + Some(value) => { + hasher.update(&[1]); + value.hash_into(&mut hasher); + } + None => { + hasher.update(&[0]); + } + } + *hasher.finalize().as_bytes() +} + +/// One committed token-mixing value of a layer at a position. +#[derive(Clone, Copy, Debug)] +pub(crate) struct MixingValue<'a> { + pub kind: TensorKind, + pub index: u32, + /// ggml type and little-endian bytes; `None` where the layer kept no row. + pub value: Option<(i32, &'a [u8])>, +} + +/// A [`MixingValue`] by its digest. +#[derive(Clone, Copy, Debug)] +pub(crate) struct MixingDigest { + pub kind: TensorKind, + pub index: u32, + /// ggml type and the value's digest; `None` where the layer kept no row. + pub value: Option<(i32, ValueDigest)>, +} + +/// The mixing leaf of `layer` at `position`, over its values in leaf order +/// (inputs, stored rows, outputs, each by index). +pub(crate) fn mixing_leaf(position: u32, layer: u32, values: &[MixingValue<'_>]) -> Hash { + let digests: Vec = values + .iter() + .map(|v| MixingDigest { + kind: v.kind, + index: v.index, + value: v.value.map(|(t, bytes)| (t, ValueDigest::of(bytes))), + }) + .collect(); + mixing_leaf_of(position, layer, &digests) +} + +/// [`mixing_leaf`] from the digests of the values. +pub(crate) fn mixing_leaf_of(position: u32, layer: u32, values: &[MixingDigest]) -> Hash { + let (stored, rest): (Vec, Vec) = values + .iter() + .partition(|v| v.kind == TensorKind::MixingStored); + mixing_leaf_from( + position, + layer, + &mixing_rest(&rest), + &stored_leaf(position, layer, &stored), + ) +} + +/// The mixing leaf from its two halves: the digest of the values that are +/// not stored rows ([`mixing_rest`]) and the leaf of the stored rows +/// ([`stored_leaf`]). An attention check opens a stored row with the other +/// half alone. +pub(crate) fn mixing_leaf_from(position: u32, layer: u32, rest: &Hash, stored: &Hash) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(MIXING_DOMAIN); + hasher.update(&position.to_le_bytes()); + hasher.update(&layer.to_le_bytes()); + hasher.update(rest); + hasher.update(stored); + *hasher.finalize().as_bytes() +} + +/// The digest of a mixing leaf's values that are not stored rows, in leaf +/// order. +pub(crate) fn mixing_rest(values: &[MixingDigest]) -> Hash { + digest_list(MIXING_REST_DOMAIN, None, values) +} + +/// The digest of the recurrent state a turn of a hybrid model started from, +/// as the stage exported it: every recurrent layer's state for the turn's +/// sequence. +pub(crate) fn recurrent_state_digest(state: &[u8]) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(RECURRENT_STATE_DOMAIN); + hasher.update(&(state.len() as u64).to_le_bytes()); + hasher.update(state); + *hasher.finalize().as_bytes() +} + +/// The leaf of the rows a layer stored in the KV cache at `position`, by +/// index. It is half of the layer's mixing leaf, and a leaf of the cell's +/// digest ([`cell_digest`]). +pub(crate) fn stored_leaf(position: u32, layer: u32, stored: &[MixingDigest]) -> Hash { + digest_list(STORED_DOMAIN, Some((position, layer)), stored) +} + +/// The digest of a KV cell a stage wrote at one position: the Merkle root +/// over its layers' [`stored_leaf`]s, in layer order. A cell's rows of one +/// layer are opened with that leaf's path. +pub(crate) fn cell_digest(stored_leaves: Vec) -> Result { + Ok(MerkleTree::new(stored_leaves)?.root()) +} + +/// The digest of every leaf a stage committed at one position when it +/// computed it, in slot order. A prefix leaf binds it ([`prefix_leaf`]), so +/// a client can open a leaf of a position the turn read from cache: the +/// node sends the position's leaves, and they must hash to this digest. +pub(crate) fn position_digest(leaves: &[Hash]) -> Hash { + let mut h = blake3::Hasher::new(); + h.update(POSITION_DOMAIN); + h.update(&(leaves.len() as u64).to_le_bytes()); + for leaf in leaves { + h.update(leaf); + } + *h.finalize().as_bytes() +} + +/// The leaf of one KV cell that a turn read below its first position, in the +/// tree a stage commits as the prefix of the turn: the position the cell +/// holds, the index of the cell in its stream of the cache, the digest of +/// what the cell stores ([`cell_digest`]), and the digest of the leaves the +/// stage committed when it computed the position ([`position_digest`]). +pub(crate) fn prefix_leaf( + position: i32, + cell: u32, + cell_digest: &Hash, + position_digest: &Hash, +) -> Hash { + let mut h = blake3::Hasher::new(); + h.update(PREFIX_DOMAIN); + h.update(&position.to_le_bytes()); + h.update(&cell.to_le_bytes()); + h.update(cell_digest); + h.update(position_digest); + *h.finalize().as_bytes() +} + +/// The digest of the tokens of a turn's cached prefix, from position 0. The +/// stage that holds layer 0 commits it with the prefix, so the prompt a +/// client checks covers the tokens the turn did not compute. +pub(crate) fn prefix_tokens_digest(tokens: &[i32]) -> Hash { + let mut h = blake3::Hasher::new(); + h.update(PREFIX_TOKENS_DOMAIN); + h.update(&(tokens.len() as u64).to_le_bytes()); + for token in tokens { + h.update(&token.to_le_bytes()); + } + *h.finalize().as_bytes() +} + +fn digest_list(domain: &[u8], at: Option<(u32, u32)>, values: &[MixingDigest]) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(domain); + if let Some((position, layer)) = at { + hasher.update(&position.to_le_bytes()); + hasher.update(&layer.to_le_bytes()); + } + hasher.update(&(values.len() as u32).to_le_bytes()); + for v in values { + hasher.update(&v.kind.code().to_le_bytes()); + hasher.update(&v.index.to_le_bytes()); + match v.value { + Some((ggml_type, value)) => { + hasher.update(&[1]); + hasher.update(&ggml_type.to_le_bytes()); + value.hash_into(&mut hasher); + } + None => { + hasher.update(&[0]); + } + } + } + *hasher.finalize().as_bytes() +} + +fn node(left: &Hash, right: &Hash) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(NODE_DOMAIN); + hasher.update(left); + hasher.update(right); + *hasher.finalize().as_bytes() +} + +/// All levels of the tree, leaves first. An odd node is carried up unchanged. +pub(crate) struct MerkleTree { + levels: Vec>, +} + +impl MerkleTree { + pub fn new(leaves: Vec) -> Result { + if leaves.is_empty() { + bail!("a receipt needs at least one leaf"); + } + let mut levels = vec![leaves]; + while levels.last().is_some_and(|level| level.len() > 1) { + let below = levels.last().expect("non-empty"); + let above = below + .chunks(2) + .map(|pair| { + if pair.len() == 2 { + node(&pair[0], &pair[1]) + } else { + pair[0] + } + }) + .collect(); + levels.push(above); + } + Ok(Self { levels }) + } + + pub fn root(&self) -> Hash { + self.levels.last().expect("non-empty")[0] + } + + pub fn leaf_count(&self) -> u64 { + self.levels[0].len() as u64 + } + + pub fn leaf(&self, index: u64) -> Option { + self.levels[0].get(usize::try_from(index).ok()?).copied() + } + + /// Sibling hashes from the leaf up; `None` marks a carried odd node. + pub fn path(&self, index: u64) -> Result>> { + let mut index = usize::try_from(index)?; + if index >= self.levels[0].len() { + bail!("leaf {index} outside a tree of {}", self.levels[0].len()); + } + let mut path = Vec::new(); + for level in &self.levels[..self.levels.len() - 1] { + path.push(level.get(index ^ 1).copied()); + index /= 2; + } + Ok(path) + } + + /// Bytes the tree keeps in memory. + pub fn bytes(&self) -> usize { + self.levels.iter().map(|level| level.len() * 32).sum() + } +} + +/// Encodes a path for the wire: carried levels are the empty string. +pub(crate) fn encode_path(path: &[Option]) -> Vec { + path.iter() + .map(|h| h.map(hex::encode).unwrap_or_default()) + .collect() +} + +/// Which levels of the path to `index` in a tree of `leaf_count` leaves +/// have a sibling (`true`) and which carry an odd node up (`false`). +pub(crate) fn path_shape(index: u64, leaf_count: u64) -> Result> { + if index >= leaf_count { + bail!("leaf {index} outside a tree of {leaf_count}"); + } + let (mut index, mut width) = (index, leaf_count); + let mut shape = Vec::new(); + while width > 1 { + shape.push((index ^ 1) < width); + index /= 2; + width = width.div_ceil(2); + } + Ok(shape) +} + +/// Recomputes the root from a leaf and its encoded path. The path must have +/// the shape of the tree the receipt names: a free choice of where siblings +/// sit would let one index open two different leaves. +pub(crate) fn root_from_path( + leaf: Hash, + index: u64, + leaf_count: u64, + path: &[String], +) -> Result { + let shape = path_shape(index, leaf_count)?; + let fits = shape.len() == path.len() + && shape + .iter() + .zip(path) + .all(|(&sibling, hash)| sibling != hash.is_empty()); + if !fits { + bail!("the path to leaf {index} does not fit a tree of {leaf_count} leaves"); + } + let mut acc = leaf; + let mut index = index; + for sibling in path { + if !sibling.is_empty() { + let bytes: Hash = hex_array(sibling, "a path sibling")?; + acc = if index.is_multiple_of(2) { + node(&acc, &bytes) + } else { + node(&bytes, &acc) + }; + } + index /= 2; + } + Ok(acc) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::layer_tensors::f32_bytes; + + fn leaf(i: u32) -> Hash { + residual_leaf(i, 0, None, Some(&f32_bytes(&[i as f32, 1.0]))) + } + + fn digest(kind: TensorKind, index: u32, byte: u8) -> MixingDigest { + MixingDigest { + kind, + index, + value: Some((1, ValueDigest::of(&[byte; 8]))), + } + } + + #[test] + fn stored_rows_open_with_the_other_half_alone() { + let values = [ + digest(TensorKind::MixingInput, 0, 1), + digest(TensorKind::MixingStored, 0, 2), + digest(TensorKind::MixingStored, 1, 3), + digest(TensorKind::MixingOutput, 0, 4), + ]; + let rest = mixing_rest(&[values[0], values[3]]); + let stored = stored_leaf(7, 2, &values[1..3]); + assert_eq!( + mixing_leaf_of(7, 2, &values), + mixing_leaf_from(7, 2, &rest, &stored) + ); + let changed = digest(TensorKind::MixingStored, 1, 9); + assert_ne!(stored_leaf(7, 2, &[values[1], changed]), stored); + assert_ne!( + stored_leaf(8, 2, &values[1..3]), + stored, + "binds the position" + ); + assert_ne!(stored_leaf(7, 3, &values[1..3]), stored, "binds the layer"); + } + + #[test] + fn every_path_reaches_the_root() { + for n in [1u32, 2, 3, 5, 8, 13] { + let leaves: Vec = (0..n).map(leaf).collect(); + let tree = MerkleTree::new(leaves.clone()).unwrap(); + for (i, l) in leaves.iter().enumerate() { + let path = encode_path(&tree.path(i as u64).unwrap()); + assert_eq!( + root_from_path(*l, i as u64, u64::from(n), &path).unwrap(), + tree.root(), + "n={n} i={i}" + ); + } + } + } + + #[test] + fn a_changed_value_breaks_the_path() { + let leaves: Vec = (0..6).map(leaf).collect(); + let tree = MerkleTree::new(leaves).unwrap(); + let path = encode_path(&tree.path(2).unwrap()); + let forged = residual_leaf(2, 0, None, Some(&f32_bytes(&[2.0001, 1.0]))); + assert_ne!(root_from_path(forged, 2, 6, &path).unwrap(), tree.root()); + } + + #[test] + fn one_index_cannot_open_two_leaves() { + // A root over [b, a] would verify both a (path "", b) and b (path a) + // at index 2 if the auditor let the prover choose where siblings sit. + let (a, b) = (leaf(1), leaf(2)); + let root = node(&b, &a); + let carried = vec![String::new(), hex::encode(b)]; + let direct = vec![hex::encode(a)]; + for leaf_count in [3, 4, 5, 6] { + let opened = [ + root_from_path(a, 2, leaf_count, &carried), + root_from_path(b, 2, leaf_count, &direct), + ]; + assert!( + opened + .iter() + .filter(|r| r.as_ref().ok() == Some(&root)) + .count() + < 2, + "leaf_count {leaf_count}" + ); + } + } + + #[test] + fn path_shapes_follow_the_tree() { + assert_eq!(path_shape(0, 1).unwrap(), Vec::::new()); + assert_eq!(path_shape(4, 5).unwrap(), vec![false, false, true]); + assert_eq!(path_shape(2, 3).unwrap(), vec![false, true]); + assert!(path_shape(5, 5).is_err()); + for n in [1u64, 2, 3, 5, 8, 13] { + let tree = MerkleTree::new((0..n as u32).map(leaf).collect()).unwrap(); + for i in 0..n { + let path = tree.path(i).unwrap(); + let shape: Vec = path.iter().map(Option::is_some).collect(); + assert_eq!(shape, path_shape(i, n).unwrap(), "n={n} i={i}"); + } + } + } + + #[test] + fn absent_and_empty_residuals_differ() { + assert_ne!( + residual_leaf(3, 1, None, None), + residual_leaf(3, 1, None, Some(&[])) + ); + } + + #[test] + fn the_token_is_part_of_the_leaf() { + let values = f32_bytes(&[1.0]); + let leaf = |token| residual_leaf(0, 0, token, Some(&values)); + assert_ne!(leaf(Some(7)), leaf(Some(8))); + assert_ne!(leaf(Some(7)), leaf(None)); + } + + #[test] + fn mixing_values_bind_type_and_presence() { + let bytes = [1u8, 2, 3, 4]; + let value = |ggml_type, present: bool| MixingValue { + kind: TensorKind::MixingStored, + index: 0, + value: present.then_some((ggml_type, &bytes[..])), + }; + let a = mixing_leaf(1, 2, &[value(1, true)]); + assert_ne!(a, mixing_leaf(1, 2, &[value(8, true)])); + assert_ne!(a, mixing_leaf(1, 2, &[value(1, false)])); + assert_ne!(a, mixing_leaf(1, 3, &[value(1, true)])); + let mut other = value(1, true); + other.kind = TensorKind::MixingOutput; + assert_ne!(a, mixing_leaf(1, 2, &[other])); + } + + #[test] + fn digests_from_the_device_make_the_same_leaves() { + // more than one BLAKE3 chunk, as a device hashes it + let values = f32_bytes(&(0..2560).map(|i| i as f32 * 0.5).collect::>()); + let digest = ValueDigest::of(&values); + assert_eq!(digest.len, 10240); + assert_eq!( + residual_leaf(3, 4, None, Some(&values)), + residual_leaf_of(3, 4, None, Some(digest)) + ); + let value = MixingValue { + kind: TensorKind::MixingStored, + index: 1, + value: Some((1, &values[..])), + }; + let by_digest = MixingDigest { + kind: TensorKind::MixingStored, + index: 1, + value: Some((1, digest)), + }; + assert_eq!( + mixing_leaf(3, 4, &[value]), + mixing_leaf_of(3, 4, &[by_digest]) + ); + // the length is bound as well as the hash + let short = ValueDigest { + len: 10236, + ..digest + }; + assert_ne!( + residual_leaf_of(3, 4, None, Some(digest)), + residual_leaf_of(3, 4, None, Some(short)) + ); + } + + #[test] + fn slots_order_residuals_and_mixing_by_layer() { + assert_eq!(slots_per_position(18, 36), 37); + assert_eq!(residual_slot(18, 18), 0); + assert_eq!(mixing_slot(18, 18), 1); + assert_eq!(residual_slot(36, 18), 36); + assert_eq!(leaf_index(11, 36, 10, 37), 73); + } +} diff --git a/crates/skippy-receipts/src/coverage.rs b/crates/skippy-receipts/src/coverage.rs new file mode 100644 index 00000000..f13cd178 --- /dev/null +++ b/crates/skippy-receipts/src/coverage.rs @@ -0,0 +1,222 @@ +//! Whether this verifier can audit a receipt at all. +//! +//! An audit needs the node's runtime, a rounding profile for every weight +//! type each stage multiplies on its backend, and for the output head's +//! weights on the final stage's backend, a KV cache whose rows the +//! attention check covers ([`crate::cache_types::AUDITED`]), and a +//! reference decoding of the output head. When one is missing the checks +//! would fail an honest node, so the receipt is not audited instead: an +//! audit that cannot run says nothing about the node +//! (`docs/design/RECEIPTS.md`). +//! +//! A node can choose a runtime or backend no verifier covers and so never +//! be audited. Its receipts then count as unaudited turns, which a client's +//! trust policy can weigh, and never as passes. + +use crate::ggml_types::type_name; +use crate::head::head_weight; +use crate::rounding_profiles::{BackendFamily, unprofiled}; +use crate::weights::WeightFile; +use crate::wire::{RECEIPT_VERSION, Receipt}; + +/// Why this verifier, which runs `runtime`, cannot audit `receipt`, if it +/// cannot. +/// +/// Everything this reads is in the receipt, so it is decided before the +/// challenge is sent: a node cannot wait for the challenge and then become +/// unauditable. +pub fn unauditable(receipt: &Receipt, weights: &WeightFile, runtime: &str) -> Option { + if receipt.version != RECEIPT_VERSION { + return Some(format!( + "the receipt is version {}, and this verifier checks version {RECEIPT_VERSION}", + receipt.version + )); + } + if let Some(binding) = &receipt.binding + && binding.runtime != runtime + { + return Some(format!( + "the node ran {}, and this verifier runs {runtime}", + binding.runtime + )); + } + for stage in &receipt.stages { + if let Some(cache_type) = stage + .cache_types + .iter() + .find(|name| !crate::cache_types::audited_name(name)) + { + return Some(format!( + "stage {} stored KV rows of type {cache_type}: an audit covers a cache of \ + f16 or f32 rows, and no quantized one", + stage.stage_index + )); + } + let Some(family) = BackendFamily::of(&stage.backend) else { + return Some(format!( + "stage {} ran on backend {}, whose rounding no profile models: an audit \ + covers CPU and CUDA stages", + stage.stage_index, stage.backend + )); + }; + let layers = stage.layer_start..stage.layer_end; + let multiplied = weights + .tensors + .values() + .filter(|t| t.is_matrix() && t.layer().is_some_and(|l| layers.contains(&l))) + .map(|t| (t.name.as_str(), t.ggml_type)); + if let Some(reason) = unprofiled(family, multiplied) { + return Some(reason); + } + } + let tensor = weights.tensors.get(head_weight(weights))?; + if !crate::dequant::supports(tensor.ggml_type) { + return Some(format!( + "no reference decoding of {} output weights", + type_name(tensor.ggml_type) + )); + } + // the head check rounds the final residual as the final stage's backend + // does for the head's weights + let family = BackendFamily::of(&receipt.stages.last()?.backend)?; + unprofiled(family, [(tensor.name.as_str(), tensor.ggml_type)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ggml_types::{GGML_F16, GGML_F32, GGML_Q4_1, GGML_Q8_0}; + use crate::turn::TurnBinding; + use crate::weights::test_gguf; + use crate::wire::{RECEIPT_VERSION, StageCommitment}; + + const RUNTIME: &str = "skippy-abi 1.2.3"; + + fn receipt(backend: &str, runtime: Option<&str>) -> Receipt { + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 2, + tokens: vec![1, 2], + generation_start: 1, + final_token: None, + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 1, + root: "00".into(), + leaf_count: 1, + backend: backend.into(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: runtime.map(|runtime| TurnBinding { + client_key: String::new(), + parent: None, + runtime: runtime.into(), + sampler: crate::turn::GREEDY.into(), + node_key: String::new(), + turn_root: String::new(), + signature: String::new(), + }), + } + } + + /// Only the tensor types matter here, so the tensors are written as f32 + /// and given their types after. Layer 1, which no stage of the receipt + /// holds, has a type without profiles. + fn weights(layer_type: u32, head_type: u32) -> WeightFile { + let names = [ + "blk.0.attn_q.weight", + "blk.1.attn_q.weight", + "output.weight", + ]; + let tensors: Vec<_> = names + .iter() + .map(|name| (*name, vec![32, 4], vec![0.0; 128])) + .collect(); + let mut weights = test_gguf::open(&[], &tensors); + for (name, ggml_type) in names.iter().zip([layer_type, GGML_Q4_1, head_type]) { + weights.tensors.get_mut(*name).unwrap().ggml_type = ggml_type; + } + weights + } + + #[test] + fn a_covered_receipt_is_auditable() { + let weights = weights(GGML_Q8_0, GGML_Q8_0); + let bound = receipt("CUDA0", Some(RUNTIME)); + assert_eq!(unauditable(&bound, &weights, RUNTIME), None); + assert_eq!(unauditable(&receipt("CPU", None), &weights, RUNTIME), None); + } + + #[test] + fn what_this_verifier_cannot_check_is_not_audited() { + let covered = weights(GGML_Q8_0, GGML_F32); + let other = receipt("CPU", Some("skippy-abi 1.2.4")); + assert!(unauditable(&other, &covered, RUNTIME).is_some()); + // a backend without measured rounding profiles: an honest Vulkan + // node fails audits, so its receipts are not audited, also when a + // node built before Vulkan lost its profiles still issues them + for backend in ["ROCm0", "Metal", "Vulkan0", "Vulkan1"] { + let reason = unauditable(&receipt(backend, None), &covered, RUNTIME).unwrap(); + assert!( + reason.contains(backend) && reason.contains("no profile models"), + "{reason}" + ); + } + let q4_1 = weights(GGML_Q4_1, GGML_F32); + let reason = unauditable(&receipt("CUDA0", None), &q4_1, RUNTIME).unwrap(); + assert!(reason.contains("blk.0.attn_q.weight"), "{reason}"); + let head = weights(GGML_Q8_0, 19); + assert!(unauditable(&receipt("CPU", None), &head, RUNTIME).is_some()); + } + + /// CUDA sums f16 products in half precision, which no profile models: + /// an honest node with f16 weights failed every audit. A receipt of + /// such a stage is not audited, and neither is one whose final stage + /// multiplies f16 output weights on CUDA. The CPU takes the f32 + /// activation of f16 weights as it is, and is audited. + #[test] + fn f16_weights_on_cuda_are_not_audited() { + let f16 = weights(GGML_F16, GGML_F16); + let reason = unauditable(&receipt("CUDA0", None), &f16, RUNTIME).unwrap(); + assert!( + reason.contains("f16 weights (blk.0.attn_q.weight) on Cuda"), + "{reason}" + ); + assert_eq!(unauditable(&receipt("CPU", None), &f16, RUNTIME), None); + let f16_head = weights(GGML_Q8_0, GGML_F16); + let reason = unauditable(&receipt("CUDA0", None), &f16_head, RUNTIME).unwrap(); + assert!(reason.contains("(output.weight) on Cuda"), "{reason}"); + assert_eq!(unauditable(&receipt("CPU", None), &f16_head, RUNTIME), None); + } + + #[test] + fn another_receipt_version_or_cache_type_is_not_audited() { + let covered = weights(GGML_Q8_0, GGML_F32); + let mut old = receipt("CPU", None); + old.version = RECEIPT_VERSION - 1; + let reason = unauditable(&old, &covered, RUNTIME).unwrap(); + assert!(reason.contains("version"), "{reason}"); + // a cache that is not quantized is audited, and no other: an honest + // stage with a quantized cache fails the loose attention check + for (cache_type, audited) in [ + ("f16", true), + ("f32", true), + ("q8_0", false), + ("q4_0", false), + ("q4_1", false), + ("type39", false), + ] { + let mut named = receipt("CPU", None); + named.stages[0].cache_types = vec![cache_type.into()]; + let reason = unauditable(&named, &covered, RUNTIME); + assert_eq!(reason.is_none(), audited, "{cache_type}: {reason:?}"); + } + } +} diff --git a/crates/skippy-receipts/src/dequant.rs b/crates/skippy-receipts/src/dequant.rs new file mode 100644 index 00000000..a16dd830 --- /dev/null +++ b/crates/skippy-receipts/src/dequant.rs @@ -0,0 +1,517 @@ +//! Reference dequantization of GGUF weight rows, in f64, following ggml's +//! `dequantize_row_*` for each format the verifier checks. +//! +//! The values are exact: every format stores small integers and f16 +//! scales, so f64 holds the products ggml computes in f32 without +//! rounding. The matmul check compares them with the node's output at a +//! tolerance that covers the backend's own rounding. +//! +//! A stored KV row is decoded the same way ([`crate::cache_types`]), by the +//! client and by the node. + +use anyhow::{Result, bail}; +use half::f16; + +use crate::ggml_types::{ + GGML_BF16, GGML_F16, GGML_F32, GGML_IQ4_NL, GGML_IQ4_XS, GGML_Q2_K, GGML_Q3_K, GGML_Q4_0, + GGML_Q4_1, GGML_Q4_K, GGML_Q5_0, GGML_Q5_1, GGML_Q5_K, GGML_Q6_K, GGML_Q8_0, type_layout, + type_name, +}; + +/// The non-linear 4-bit levels of IQ4_NL. +const IQ4_NL_LEVELS: [i8; 16] = [ + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, +]; + +/// One IQ4_XS block of 256 values: an f16 scale, a 6-bit scale per 32 +/// values (low 4 bits in `scales_l`, high 2 in `scales_h`), and IQ4_NL +/// levels (`dequantize_row_iq4_xs`). +fn iq4_xs(block: &[u8; 136], out: &mut Vec) { + let d = half(&block[..2]); + let scales_h = u16::from_le_bytes([block[2], block[3]]); + let scales_l = &block[4..8]; + for (ib, qs) in block[8..].as_chunks::<16>().0.iter().enumerate() { + let low = (scales_l[ib / 2] >> (4 * (ib % 2))) & 0xF; + let high = ((scales_h >> (2 * ib)) & 3) as u8; + let dl = d * f64::from(i32::from(low | (high << 4)) - 32); + let level = |q: u8| dl * f64::from(IQ4_NL_LEVELS[usize::from(q)]); + out.extend(qs.iter().map(|&q| level(q & 0xF))); + out.extend(qs.iter().map(|&q| level(q >> 4))); + } +} + +fn half(bytes: &[u8]) -> f64 { + f64::from(f16::from_le_bytes([bytes[0], bytes[1]]).to_f32()) +} + +/// Whether [`dequantize_row`] decodes `ggml_type`. +pub(crate) fn supports(ggml_type: u32) -> bool { + matches!( + ggml_type, + GGML_F32 + | GGML_F16 + | GGML_BF16 + | GGML_Q4_0 + | GGML_Q4_1 + | GGML_Q5_0 + | GGML_Q5_1 + | GGML_Q8_0 + | GGML_Q2_K + | GGML_Q3_K + | GGML_Q4_K + | GGML_Q5_K + | GGML_Q6_K + | GGML_IQ4_NL + | GGML_IQ4_XS + ) +} + +/// Checks that `raw` is a row of `n` values of `ggml_type`: whole blocks, +/// and all of them. The header of the claimed GGUF gives `n`, so nothing is +/// allocated for it before the bytes are there. +fn check_row(ggml_type: u32, raw: &[u8], n: usize) -> Result<()> { + if !supports(ggml_type) { + bail!( + "no audit profile for weight type {} yet", + type_name(ggml_type) + ); + } + let Some((block, bytes)) = type_layout(ggml_type) else { + bail!("weight type {} has no layout", type_name(ggml_type)); + }; + let (block, bytes) = (usize::try_from(block)?, usize::try_from(bytes)?); + let expected = n + .is_multiple_of(block) + .then(|| (n / block).checked_mul(bytes)) + .flatten(); + if expected != Some(raw.len()) { + bail!( + "a row of {n} {} values is not {} bytes", + type_name(ggml_type), + raw.len() + ); + } + Ok(()) +} + +/// Reference dequantization of one row of `n` values. +pub(crate) fn dequantize_row(ggml_type: u32, raw: &[u8], n: usize) -> Result> { + check_row(ggml_type, raw, n)?; + let mut out = Vec::with_capacity(n); + match ggml_type { + GGML_F32 => out.extend( + raw.as_chunks::<4>() + .0 + .iter() + .map(|c| f64::from(f32::from_le_bytes(*c))), + ), + GGML_F16 => out.extend(raw.as_chunks::<2>().0.iter().map(|c| half(c))), + GGML_BF16 => out.extend( + raw.as_chunks::<2>() + .0 + .iter() + .map(|c| f64::from(half::bf16::from_le_bytes(*c).to_f32())), + ), + GGML_Q4_0 => raw + .as_chunks::<18>() + .0 + .iter() + .for_each(|b| q4_0(b, &mut out)), + GGML_Q4_1 => raw + .as_chunks::<20>() + .0 + .iter() + .for_each(|b| q4_1(b, &mut out)), + GGML_Q5_0 => raw + .as_chunks::<22>() + .0 + .iter() + .for_each(|b| q5_0(b, &mut out)), + GGML_Q5_1 => raw + .as_chunks::<24>() + .0 + .iter() + .for_each(|b| q5_1(b, &mut out)), + GGML_Q8_0 => { + for block in raw.as_chunks::<34>().0 { + let d = half(block); + out.extend(block[2..].iter().map(|&q| d * f64::from(q as i8))); + } + } + GGML_Q2_K => raw + .as_chunks::<84>() + .0 + .iter() + .for_each(|b| q2_k(b, &mut out)), + GGML_Q3_K => raw + .as_chunks::<110>() + .0 + .iter() + .for_each(|b| q3_k(b, &mut out)), + GGML_Q4_K => raw + .as_chunks::<144>() + .0 + .iter() + .for_each(|b| k_min_blocks(b, None, &b[16..], &mut |s| k_min_values(s, &mut out))), + GGML_Q5_K => raw.as_chunks::<176>().0.iter().for_each(|b| { + k_min_blocks(b, Some(&b[16..48]), &b[48..], &mut |s| { + k_min_values(s, &mut out); + }); + }), + GGML_Q6_K => raw + .as_chunks::<210>() + .0 + .iter() + .for_each(|b| q6_k(b, &mut out)), + GGML_IQ4_NL => { + for block in raw.as_chunks::<18>().0 { + let d = half(block); + let level = |q: u8| d * f64::from(IQ4_NL_LEVELS[usize::from(q)]); + out.extend(block[2..].iter().map(|&q| level(q & 0xF))); + out.extend(block[2..].iter().map(|&q| level(q >> 4))); + } + } + GGML_IQ4_XS => raw + .as_chunks::<136>() + .0 + .iter() + .for_each(|b| iq4_xs(b, &mut out)), + other => bail!("no audit profile for weight type {} yet", type_name(other)), + } + if out.len() != n { + bail!("row decoded to {} values, expected {n}", out.len()); + } + Ok(out) +} + +/// `d`, 16 bytes of nibbles: low nibbles are values 0..16, high 16..32. +fn q4_0(b: &[u8; 18], out: &mut Vec) { + let d = half(b); + out.extend(b[2..].iter().map(|&q| d * (f64::from(q & 0xF) - 8.0))); + out.extend(b[2..].iter().map(|&q| d * (f64::from(q >> 4) - 8.0))); +} + +fn q4_1(b: &[u8; 20], out: &mut Vec) { + let (d, m) = (half(b), half(&b[2..])); + out.extend(b[4..].iter().map(|&q| d * f64::from(q & 0xF) + m)); + out.extend(b[4..].iter().map(|&q| d * f64::from(q >> 4) + m)); +} + +/// The fifth bit of each value, from a 32-bit mask. +fn high_bits(qh: u32, j: usize) -> (u8, u8) { + let low = (((qh >> j) << 4) & 0x10) as u8; + let high = ((qh >> (j + 12)) & 0x10) as u8; + (low, high) +} + +fn q5_0(b: &[u8; 22], out: &mut Vec) { + let d = half(b); + let qh = u32::from_le_bytes([b[2], b[3], b[4], b[5]]); + let qs = &b[6..]; + let mut hi = [0.0; 16]; + for (j, &q) in qs.iter().enumerate() { + let (h0, h1) = high_bits(qh, j); + out.push(d * (f64::from((q & 0xF) | h0) - 16.0)); + hi[j] = d * (f64::from((q >> 4) | h1) - 16.0); + } + out.extend(hi); +} + +fn q5_1(b: &[u8; 24], out: &mut Vec) { + let (d, m) = (half(b), half(&b[2..])); + let qh = u32::from_le_bytes([b[4], b[5], b[6], b[7]]); + let qs = &b[8..]; + let mut hi = [0.0; 16]; + for (j, &q) in qs.iter().enumerate() { + let (h0, h1) = high_bits(qh, j); + out.push(d * f64::from((q & 0xF) | h0) + m); + hi[j] = d * f64::from((q >> 4) | h1) + m; + } + out.extend(hi); +} + +/// `scales[16]`, `qs[64]`, `d`, `dmin`: 2-bit values with a 4-bit scale +/// and minimum per 16. +fn q2_k(b: &[u8; 84], out: &mut Vec) { + let (scales, qs) = (&b[..16], &b[16..80]); + let (d, dmin) = (half(&b[80..]), half(&b[82..])); + let mut is = 0; + for q in qs.as_chunks::<32>().0 { + for shift in (0..8).step_by(2) { + for half_block in [&q[..16], &q[16..]] { + let sc = scales[is]; + is += 1; + let (dl, ml) = (d * f64::from(sc & 0xF), dmin * f64::from(sc >> 4)); + out.extend( + half_block + .iter() + .map(|&v| dl * f64::from((v >> shift) & 3) - ml), + ); + } + } + } +} + +/// `hmask[32]`, `qs[64]`, `scales[12]`, `d`: 3-bit values (two low bits +/// and a high bit that, when clear, subtracts 4) with a 6-bit scale per 16. +fn q3_k(b: &[u8; 110], out: &mut Vec) { + let (hmask, qs) = (&b[..32], &b[32..96]); + let d = half(&b[108..]); + let word = |i: usize| u32::from_le_bytes([b[96 + i], b[97 + i], b[98 + i], b[99 + i]]); + let (a0, a1, tmp) = (word(0), word(4), word(8)); + let (kmask1, kmask2) = (0x0303_0303u32, 0x0f0f_0f0fu32); + let aux = [ + (a0 & kmask2) | ((tmp & kmask1) << 4), + (a1 & kmask2) | (((tmp >> 2) & kmask1) << 4), + ((a0 >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4), + ((a1 >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4), + ]; + let scales: Vec = aux + .iter() + .flat_map(|w| w.to_le_bytes()) + .map(|v| v as i8) + .collect(); + let mut is = 0; + let mut m = 1u8; + for q in qs.as_chunks::<32>().0 { + for shift in (0..8).step_by(2) { + for offset in [0, 16] { + let dl = d * f64::from(i32::from(scales[is]) - 32); + is += 1; + out.extend((offset..offset + 16).map(|l| { + let low = i32::from((q[l] >> shift) & 3); + let high = if hmask[l] & m != 0 { 0 } else { 4 }; + dl * f64::from(low - high) + })); + } + m <<= 1; + } + } +} + +/// The 6-bit scale and minimum of sub-block `j` of a Q4_K or Q5_K block. +fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) { + if j < 4 { + (q[j] & 63, q[j + 4] & 63) + } else { + ( + (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4), + (q[j + 4] >> 4) | ((q[j] >> 6) << 4), + ) + } +} + +/// One sub-block of 32 values of a weight with a minimum per 32: value +/// `k` is `scale · quants[k] − min`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct MinBlock { + pub scale: f64, + pub min: f64, + pub quants: [u8; 32], +} + +/// The sub-blocks of a row of a weight with a minimum per 32 values +/// (Q4_K, Q5_K), for the kernels that apply the minimum to a sum of the +/// activation rather than to each value. +pub(crate) fn min_blocks(ggml_type: u32, raw: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut push = |block| out.push(block); + match ggml_type { + GGML_Q4_K => raw + .as_chunks::<144>() + .0 + .iter() + .for_each(|b| k_min_blocks(b, None, &b[16..], &mut push)), + GGML_Q5_K => raw + .as_chunks::<176>() + .0 + .iter() + .for_each(|b| k_min_blocks(b, Some(&b[16..48]), &b[48..], &mut push)), + other => bail!("{} weights have no minimum per 32 values", type_name(other)), + } + Ok(out) +} + +/// The eight sub-blocks of a Q4_K block (`d`, `dmin`, `scales[12]`, +/// `qs[128]`: 4-bit values with a 6-bit scale and minimum per 32), or of a +/// Q5_K block with a fifth bit per value from `qh[32]`. +fn k_min_blocks(b: &[u8], qh: Option<&[u8]>, qs: &[u8], visit: &mut impl FnMut(MinBlock)) { + let (d, dmin) = (half(b), half(&b[2..])); + let scales = &b[4..16]; + for (i, q) in qs.as_chunks::<32>().0.iter().enumerate() { + for high_nibble in [false, true] { + let j = 2 * i + usize::from(high_nibble); + let (s, m) = scale_min_k4(j, scales); + let mut quants = [0u8; 32]; + for (k, (out, &v)) in quants.iter_mut().zip(q).enumerate() { + let low = if high_nibble { v >> 4 } else { v & 0xF }; + let fifth = qh.map_or(0, |qh| ((qh[k] >> j) & 1) << 4); + *out = low | fifth; + } + visit(MinBlock { + scale: d * f64::from(s), + min: dmin * f64::from(m), + quants, + }); + } + } +} + +fn k_min_values(block: MinBlock, out: &mut Vec) { + let MinBlock { scale, min, quants } = block; + out.extend(quants.iter().map(|&q| scale * f64::from(q) - min)); +} + +/// `ql[128]`, `qh[64]`, `scales[16]` (i8), `d`: 6-bit values less 32 with +/// an 8-bit scale per 16. +fn q6_k(b: &[u8; 210], out: &mut Vec) { + let d = half(&b[208..]); + for n in 0..2 { + let ql = &b[n * 64..n * 64 + 64]; + let qh = &b[128 + n * 32..128 + n * 32 + 32]; + let sc = &b[192 + n * 8..192 + n * 8 + 8]; + let mut y = [0.0; 128]; + for l in 0..32 { + let is = l / 16; + let value = |low: u8, shift: u32| { + f64::from(i32::from(low | (((qh[l] >> shift) & 3) << 4)) - 32) + }; + let scale = |k: usize| d * f64::from(sc[is + k] as i8); + y[l] = scale(0) * value(ql[l] & 0xF, 0); + y[l + 32] = scale(2) * value(ql[l + 32] & 0xF, 2); + y[l + 64] = scale(4) * value(ql[l] >> 4, 4); + y[l + 96] = scale(6) * value(ql[l + 32] >> 4, 6); + } + out.extend(y); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f16_bytes(v: f32) -> [u8; 2] { + f16::from_f32(v).to_le_bytes() + } + + #[test] + fn q8_0_block_dequantizes_to_scale_times_quant() { + let mut block = f16_bytes(0.5).to_vec(); + block.extend((0..32).map(|i| (i as i8 - 16) as u8)); + let row = dequantize_row(GGML_Q8_0, &block, 32).unwrap(); + assert_eq!(row[0], -8.0); + assert_eq!(row[31], 7.5); + } + + #[test] + fn q4_0_and_q4_1_split_nibbles_into_halves() { + let mut block = f16_bytes(2.0).to_vec(); + block.extend([0x9Fu8; 16]); + let row = dequantize_row(GGML_Q4_0, &block, 32).unwrap(); + assert_eq!((row[0], row[16]), (14.0, 2.0)); + let mut block = f16_bytes(2.0).to_vec(); + block.extend(f16_bytes(-1.0)); + block.extend([0x9Fu8; 16]); + let row = dequantize_row(GGML_Q4_1, &block, 32).unwrap(); + assert_eq!((row[0], row[16]), (29.0, 17.0)); + } + + #[test] + fn q5_0_takes_the_fifth_bit_from_the_mask() { + let mut block = f16_bytes(1.0).to_vec(); + // fifth bit set for value 0 and for value 16 + 3 + block.extend((1u32 | (1 << 19)).to_le_bytes()); + block.extend([0u8; 16]); + let row = dequantize_row(GGML_Q5_0, &block, 32).unwrap(); + assert_eq!(row[0], 0.0); + assert_eq!(row[1], -16.0); + assert_eq!(row[19], 0.0); + assert_eq!(row[20], -16.0); + } + + #[test] + fn q4_k_applies_scales_and_minimums_per_32() { + let mut block = f16_bytes(1.0).to_vec(); + block.extend(f16_bytes(0.5)); + // sub-blocks 0..4: scale j + 1, minimum 2; sub-blocks 4..8: scale 1, minimum 0 + let mut scales = [0u8; 12]; + for j in 0..4 { + scales[j] = j as u8 + 1; + scales[j + 4] = 2; + scales[j + 8] = 1; + } + block.extend(scales); + block.extend([0x21u8; 128]); + let row = dequantize_row(GGML_Q4_K, &block, 256).unwrap(); + // sub-block 0 reads low nibbles (1), sub-block 1 high nibbles (2) + assert_eq!(row[0], 1.0 * 1.0 - 1.0); + assert_eq!(row[32], 2.0 * 2.0 - 1.0); + assert_eq!(row[64], 3.0 * 1.0 - 1.0); + assert_eq!(row[255], 1.0 * 2.0); + } + + #[test] + fn q6_k_subtracts_32_and_scales_per_16() { + let mut block = vec![0u8; 210]; + block[..128].fill(0x11); + block[128..192].fill(0b1010_1010); + for (i, s) in block[192..208].iter_mut().enumerate() { + *s = (i as i8 - 4) as u8; + } + block[208..].copy_from_slice(&f16_bytes(0.25)); + let row = dequantize_row(GGML_Q6_K, &block, 256).unwrap(); + // value (1 | 2 << 4) - 32 = 1 in every position + assert_eq!(row[0], 0.25 * -4.0); + assert_eq!(row[16], 0.25 * -3.0); + assert_eq!(row[32], 0.25 * -2.0); + assert_eq!(row[128], 0.25 * 4.0); + } + + #[test] + fn every_k_quant_decodes_a_whole_row() { + for (t, bytes) in [(GGML_Q2_K, 84), (GGML_Q3_K, 110), (GGML_Q5_K, 176)] { + let row = dequantize_row(t, &vec![0u8; bytes * 2], 512).unwrap(); + assert_eq!(row.len(), 512); + assert!(row.iter().all(|v| v.is_finite())); + } + let mut q3 = vec![0u8; 110]; + q3[108..].copy_from_slice(&f16_bytes(1.0)); + // every scale is 0 - 32 and every value 0 - 4: 128 everywhere + let row = dequantize_row(GGML_Q3_K, &q3, 256).unwrap(); + assert!(row.iter().all(|&v| v == 128.0), "{:?}", &row[..4]); + } + + #[test] + fn iq4_xs_joins_its_six_bit_scales_and_maps_levels() { + let mut block = vec![0u8; 136]; + block[..2].copy_from_slice(&f16_bytes(1.0)); + // sub-block 0: scale 1 | 2 << 4 = 33, so 33 - 32 = 1; sub-block 1: 0 - 32 + block[2] = 0b10; + block[4] = 0x01; + block[8] = 0x8F; + let row = dequantize_row(GGML_IQ4_XS, &block, 256).unwrap(); + assert_eq!(row[0], 113.0); + assert_eq!(row[16], 1.0); + assert_eq!(row[32], -32.0 * -127.0); + assert_eq!(row.len(), 256); + } + + #[test] + fn unknown_types_are_refused() { + assert!(dequantize_row(19, &[0u8; 50], 256).is_err()); + } + + #[test] + fn a_row_length_the_bytes_do_not_hold_is_refused_before_it_is_allocated() { + // a length a header wrapped to: no vector of it is reserved + for n in [usize::MAX, usize::MAX - 31, 1 << 60] { + assert!(dequantize_row(GGML_F32, &[0u8; 16], n).is_err(), "{n}"); + assert!(dequantize_row(GGML_Q8_0, &[0u8; 34], n).is_err(), "{n}"); + } + // not whole blocks, too few bytes, too many bytes + assert!(dequantize_row(GGML_Q8_0, &[0u8; 34], 31).is_err()); + assert!(dequantize_row(GGML_Q8_0, &[0u8; 33], 32).is_err()); + assert!(dequantize_row(GGML_F32, &[0u8; 20], 4).is_err()); + assert!(dequantize_row(GGML_F32, &[], 0).unwrap().is_empty()); + } +} diff --git a/crates/skippy-receipts/src/draw.rs b/crates/skippy-receipts/src/draw.rs new file mode 100644 index 00000000..402dbce5 --- /dev/null +++ b/crates/skippy-receipts/src/draw.rs @@ -0,0 +1,98 @@ +//! Deterministic draws from a VRF output. +//! +//! A challenge and its checked rows must be reproducible by anyone who +//! holds the VRF proof, so they cannot depend on a random number library +//! whose algorithms may change between versions. A [`DrawStream`] is the +//! BLAKE3 XOF of the VRF output under a label, read eight bytes at a time; +//! [`DrawStream::below`] draws uniformly by rejection. + +/// A stream of uniform draws, keyed by a seed and a label. +pub(crate) struct DrawStream { + reader: blake3::OutputReader, +} + +impl DrawStream { + /// `label` separates independent draws from one seed, for example the + /// challenge and the rows of each weight. + pub(crate) fn new(seed: &[u8], label: &str) -> Self { + let mut hasher = blake3::Hasher::new_derive_key("mesh-llm receipts draw v1"); + hasher.update(&(label.len() as u64).to_le_bytes()); + hasher.update(label.as_bytes()); + hasher.update(seed); + Self { + reader: hasher.finalize_xof(), + } + } + + fn next_u64(&mut self) -> u64 { + let mut bytes = [0u8; 8]; + self.reader.fill(&mut bytes); + u64::from_le_bytes(bytes) + } + + /// A uniform draw from `0..n`. `n` must be positive. + pub(crate) fn below(&mut self, n: u64) -> u64 { + assert!(n > 0, "a draw from an empty range"); + // the largest multiple of n that fits, so every residue is equally likely + let zone = u64::MAX - (u64::MAX - n + 1) % n; + loop { + let value = self.next_u64(); + if value <= zone { + return value % n; + } + } + } + + /// A uniform draw from `range`, which must not be empty. + pub(crate) fn in_range(&mut self, range: std::ops::Range) -> u32 { + let span = u64::from(range.end - range.start); + range.start + u32::try_from(self.below(span)).expect("a draw below a u32 span") + } + + /// A uniform draw from `0..1`, for an audit-rate decision. + pub(crate) fn unit(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_same_seed_and_label_give_the_same_draws() { + let draws = |seed: &[u8], label| { + let mut s = DrawStream::new(seed, label); + (0..8).map(|_| s.below(1000)).collect::>() + }; + assert_eq!(draws(b"seed", "a"), draws(b"seed", "a")); + assert_ne!(draws(b"seed", "a"), draws(b"seed", "b")); + assert_ne!(draws(b"seed", "a"), draws(b"seee", "a")); + } + + #[test] + fn draws_stay_in_range_and_cover_it() { + let mut s = DrawStream::new(b"x", "y"); + let mut seen = [false; 7]; + for _ in 0..500 { + let v = s.below(7); + seen[v as usize] = true; + } + assert!(seen.iter().all(|&s| s)); + for _ in 0..100 { + assert!((10..13).contains(&s.in_range(10..13))); + assert!((0.0..1.0).contains(&s.unit())); + } + assert_eq!(s.below(1), 0); + let _ = s.below(u64::MAX); + } + + #[test] + fn the_stream_is_pinned() { + // a change here changes every challenge and invalidates old evidence + let mut s = DrawStream::new(&[0u8; 64], "challenge"); + let first = s.next_u64(); + assert_eq!(first, DrawStream::new(&[0u8; 64], "challenge").next_u64()); + assert_eq!(first, 12_899_550_690_765_162_838); + } +} diff --git a/crates/skippy-receipts/src/error_bound.rs b/crates/skippy-receipts/src/error_bound.rs new file mode 100644 index 00000000..ec9a4449 --- /dev/null +++ b/crates/skippy-receipts/src/error_bound.rs @@ -0,0 +1,69 @@ +//! Comparing a check's error with its tolerance so that a value that is +//! not a number fails. +//! +//! `error > tolerance` is false for NaN, and `f64::max` drops a NaN +//! operand. A check written with either passes a node that opens a NaN. +//! Every comparison of an opened value goes through these instead. + +/// Whether `error` is past `tolerance`. An error that is not a number is. +pub(crate) fn exceeds(error: f64, tolerance: f64) -> bool { + error.is_nan() || error > tolerance +} + +/// Whether `error` is within `tolerance`. An error that is not a number +/// is not. +pub(crate) fn within(error: f64, tolerance: f64) -> bool { + !exceeds(error, tolerance) +} + +/// The larger of two errors; infinite when either is not a number. +pub(crate) fn worst(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::INFINITY + } else { + a.max(b) + } +} + +/// The largest of `errors`, from 0; infinite when one is not a number. +pub(crate) fn worst_of(errors: impl IntoIterator) -> f64 { + errors.into_iter().fold(0.0, worst) +} + +/// Whether every value is a number. +pub(crate) fn all_finite(values: &[f32]) -> bool { + values.iter().all(|v| v.is_finite()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_error_that_is_not_a_number_is_past_every_tolerance() { + assert!(exceeds(f64::NAN, 1e-3)); + assert!(exceeds(f64::INFINITY, 1e-3)); + assert!(exceeds(2e-3, 1e-3)); + assert!(within(1e-3, 1e-3)); + assert!(!within(f64::NAN, f64::INFINITY)); + } + + #[test] + fn the_worst_error_keeps_a_value_that_is_not_a_number() { + assert_eq!(worst(1.0, 2.0), 2.0); + assert_eq!(worst(f64::NAN, 2.0), f64::INFINITY); + assert_eq!(worst(2.0, f64::NAN), f64::INFINITY); + assert_eq!(worst_of([0.5, f64::NAN, 0.25]), f64::INFINITY); + assert_eq!(worst_of([0.5, 0.25]), 0.5); + assert_eq!(worst_of([]), 0.0); + // `f64::max`, which the checks used, drops it + assert_eq!([0.5, f64::NAN].into_iter().fold(0.0, f64::max), 0.5); + } + + #[test] + fn finite_values_hold_no_nan_or_infinity() { + assert!(all_finite(&[0.0, -1.5, f32::MAX])); + assert!(!all_finite(&[0.0, f32::NAN])); + assert!(!all_finite(&[f32::NEG_INFINITY])); + } +} diff --git a/crates/skippy-receipts/src/evidence.rs b/crates/skippy-receipts/src/evidence.rs new file mode 100644 index 00000000..21c2e892 --- /dev/null +++ b/crates/skippy-receipts/src/evidence.rs @@ -0,0 +1,350 @@ +//! Evidence of an audit, which anyone can recheck from public data: the +//! signed receipt, the challenge with the VRF proof that drew it, the +//! opening as the node sent and signed it, the VRF proof that drew the +//! checked rows, and the attention rows the node then sent and signed. +//! +//! [`Evidence::verify`] shows that neither side chose what was checked: +//! the node signed the receipt and the opening, and the client's VRF drew +//! the challenge from the turn root and the rows from the opening's bytes. +//! The checks themselves then run again on the claimed GGUF. The response +//! text is not part of it: the node does not sign the response, so the +//! comparison of the response with the sampled tokens convinces only the +//! client that received it. + +use std::collections::BTreeMap; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::attention::opening::BlockChallenge; +use crate::challenge; +use crate::turn::{self, VerifiedBinding}; +use crate::vrf; +use crate::wire::{Challenge, Opening, Receipt}; + +pub(crate) const EVIDENCE_VERSION: u32 = 1; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Evidence { + pub version: u32, + pub receipt: Receipt, + /// The challenge, with the VRF proof of the turn root in `proof`. + pub challenge: Challenge, + /// Base64 of the opening's bytes as the node sent them. + pub opening: String, + /// Hex node signature of the opening ([`turn::sign_opening`]). + pub opening_signature: String, + /// Hex VRF proof of the opening's bytes, which drew the checked rows. + pub rows_proof: String, + /// Base64 of the attention rows' bytes as the node sent them, when it + /// sent any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rows: Option, + /// Hex node signature of the rows ([`turn::sign_rows`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rows_signature: Option, +} + +/// What [`Evidence::verify`] establishes, for rerunning the checks. +pub struct Provenance { + pub binding: VerifiedBinding, + pub opening: Opening, + /// The VRF output the checked rows are drawn from. + pub rows_seed: vrf::Output, + /// The attention rows the node sent, when it sent any. Their signature + /// is checked against the blocks a recheck draws ([`SignedRows::answering`]). + pub rows: Option, +} + +impl Evidence { + pub fn new( + receipt: Receipt, + challenge: Challenge, + opening_bytes: &[u8], + opening_signature: String, + rows_proof: &vrf::Proof, + ) -> Self { + Self { + version: EVIDENCE_VERSION, + receipt, + challenge, + opening: crate::wire::encode_bytes(opening_bytes), + opening_signature, + rows_proof: hex::encode(rows_proof), + rows: None, + rows_signature: None, + } + } + + /// Adds the attention rows the node sent after the opening. + #[must_use] + pub fn with_rows(mut self, rows_bytes: &[u8], signature: Option) -> Self { + self.rows = Some(crate::wire::encode_bytes(rows_bytes)); + self.rows_signature = signature; + self + } + + pub fn opening_bytes(&self) -> Result> { + crate::wire::decode_bytes(&self.opening).context("decode the opening's bytes") + } + + /// Checks that the node signed the receipt, the opening and the rows, and that + /// the client's VRF drew the challenge and the rows. `layer_bytes` is + /// the claimed GGUF's weight bytes per executable layer, which the + /// challenge was drawn with. + pub fn verify(&self, layer_bytes: &BTreeMap) -> Result { + if self.version != EVIDENCE_VERSION { + bail!( + "evidence version {} is not {EVIDENCE_VERSION}", + self.version + ); + } + let binding = turn::verify(&self.receipt, None)?; + let proof = self + .challenge + .proof + .as_deref() + .context("the challenge carries no VRF proof")?; + let beta = vrf::verify( + &binding.client_key, + &turn::challenge_input(&binding.turn_root), + &vrf::proof_from_hex(proof)?, + ) + .context("the challenge's VRF proof")?; + let mut drawn = challenge::draw(&self.receipt, layer_bytes, &beta)?; + drawn.proof = self.challenge.proof.clone(); + if drawn != self.challenge { + bail!("the challenge is not the one the VRF of the turn root draws"); + } + let bytes = self.opening_bytes()?; + turn::verify_opening(&binding, &self.challenge, &bytes, &self.opening_signature)?; + let rows_seed = vrf::verify( + &binding.client_key, + &turn::rows_input(&bytes), + &vrf::proof_from_hex(&self.rows_proof)?, + ) + .context("the rows' VRF proof")?; + let opening = serde_json::from_slice(&bytes).context("decode the opening")?; + let rows = match &self.rows { + Some(rows) => Some(SignedRows { + bytes: crate::wire::decode_bytes(rows).context("decode the rows' bytes")?, + signature: self + .rows_signature + .clone() + .context("the rows carry no node signature")?, + proof: self.rows_proof.clone(), + }), + None => None, + }; + Ok(Provenance { + binding, + opening, + rows_seed, + rows, + }) + } +} + +/// The attention rows of evidence, as the node sent and signed them. +pub struct SignedRows { + bytes: Vec, + signature: String, + /// Hex VRF proof the client sent with its block request. + proof: String, +} + +impl SignedRows { + /// The rows' bytes, once the node's signature shows it sent them in + /// answer to `blocks`: the blocks the rows' seed draws, which a + /// recheck draws again. Rows the node sent for other blocks are not + /// evidence. + pub fn answering(&self, binding: &VerifiedBinding, blocks: &BlockChallenge) -> Result<&[u8]> { + let mut asked = blocks.clone(); + asked.proof = Some(self.proof.clone()); + turn::verify_rows(binding, &asked, &self.bytes, &self.signature) + .context("the rows' signature")?; + Ok(&self.bytes) + } + + pub fn signature(&self) -> &str { + &self.signature + } +} + +#[cfg(test)] +mod tests { + use ed25519_dalek::SigningKey; + + use super::*; + use crate::turn::{BindingRequest, GREEDY}; + use crate::wire::{RECEIPT_VERSION, StageCommitment}; + + fn evidence() -> (Evidence, BTreeMap) { + let node = SigningKey::from_bytes(&[5; 32]); + let client = vrf::SecretKey::from_seed([9; 32]); + let mut receipt = Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 8, + tokens: (0..8).collect(), + generation_start: 4, + final_token: Some(9), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 4, + root: "00".into(), + leaf_count: 1, + backend: "CPU".into(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: None, + }; + turn::bind( + &mut receipt, + &BindingRequest { + client_key: client.public(), + parent: None, + runtime: "skippy-abi 0.1.77".into(), + sampler: GREEDY.into(), + }, + &node, + ); + let bound = turn::verify(&receipt, None).unwrap(); + let layer_bytes: BTreeMap = (0..4).map(|l| (l, 10)).collect(); + let (beta, proof) = client.evaluate(&turn::challenge_input(&bound.turn_root)); + let mut challenge = challenge::draw(&receipt, &layer_bytes, &beta).unwrap(); + challenge.proof = Some(hex::encode(proof)); + let bytes = br#"{"receipt_id":"r","stages":[]}"#; + let signature = turn::sign_opening(&node, &bound.turn_root, &challenge, bytes); + let (_, rows_proof) = client.evaluate(&turn::rows_input(bytes)); + let rows = br#"{"receipt_id":"r","stages":[]}"#; + let mut asked = blocks(); + asked.proof = Some(hex::encode(rows_proof)); + let rows_signature = turn::sign_rows(&node, &bound.turn_root, &asked, rows); + ( + Evidence::new(receipt, challenge, bytes, signature, &rows_proof) + .with_rows(rows, Some(rows_signature)), + layer_bytes, + ) + } + + /// The blocks the rows' seed is taken to draw. + fn blocks() -> BlockChallenge { + BlockChallenge { + receipt_id: "r".into(), + picks: vec![crate::attention::opening::BlockPick { + position: 5, + layer: 1, + blocks: vec![0], + }], + proof: None, + } + } + + #[test] + fn evidence_shows_who_chose_what() { + let (evidence, layer_bytes) = evidence(); + let provenance = evidence.verify(&layer_bytes).unwrap(); + assert_eq!(provenance.opening.receipt_id, "r"); + // a round trip through JSON keeps it valid + let text = serde_json::to_string(&evidence).unwrap(); + let back: Evidence = serde_json::from_str(&text).unwrap(); + back.verify(&layer_bytes).unwrap(); + // the rows answer the blocks the node signed them for + let rows = provenance.rows.as_ref().expect("rows"); + rows.answering(&provenance.binding, &blocks()).unwrap(); + } + + #[test] + fn rows_the_node_sent_for_other_blocks_are_not_evidence() { + let (evidence, layer_bytes) = evidence(); + let provenance = evidence.verify(&layer_bytes).unwrap(); + let rows = provenance.rows.as_ref().expect("rows"); + let mut other = blocks(); + other.picks[0].blocks = vec![1]; + assert!(rows.answering(&provenance.binding, &other).is_err()); + } + + #[test] + fn an_opening_of_another_challenge_is_not_evidence() { + // the client sent picks of its own with the true proof, got them + // opened, and shows the opening with the challenge the VRF draws + let node = SigningKey::from_bytes(&[5; 32]); + let (mut evidence, layer_bytes) = evidence(); + let bound = turn::verify(&evidence.receipt, None).unwrap(); + let mut sent = evidence.challenge.clone(); + sent.picks.truncate(1); + let bytes = evidence.opening_bytes().unwrap(); + evidence.opening_signature = turn::sign_opening(&node, &bound.turn_root, &sent, &bytes); + assert!(evidence.verify(&layer_bytes).is_err()); + } + + #[test] + fn a_challenge_picked_by_hand_is_not_evidence_though_the_node_answered_it() { + // `audit-receipt --layer` challenges one layer of the client's own + // choosing, with the true VRF proof. The node opens it and signs + // the opening of that very challenge, so every signature is good. + // Shown as evidence, the challenge is still not the one the VRF + // draws: a client could otherwise pick what an honest node's rare + // outliers fail. + let node = SigningKey::from_bytes(&[5; 32]); + let (mut evidence, layer_bytes) = evidence(); + let bound = turn::verify(&evidence.receipt, None).unwrap(); + let drawn = evidence.challenge.clone(); + evidence.challenge.picks.truncate(1); + evidence.challenge.attention = + challenge::draw_attention(&evidence.challenge.picks, b"any seed"); + assert_ne!(evidence.challenge, drawn); + let bytes = evidence.opening_bytes().unwrap(); + evidence.opening_signature = + turn::sign_opening(&node, &bound.turn_root, &evidence.challenge, &bytes); + let error = evidence + .verify(&layer_bytes) + .err() + .expect("a hand-picked challenge"); + assert!( + error.to_string().contains("not the one the VRF"), + "{error:#}" + ); + } + + #[test] + fn a_changed_part_of_the_evidence_fails() { + let (evidence, layer_bytes) = evidence(); + // a challenge the client picked by hand + let mut picked = evidence.clone(); + picked.challenge.picks[0].layer ^= 1; + assert!(picked.verify(&layer_bytes).is_err()); + // an opening the node did not send + let mut forged = evidence.clone(); + forged.opening = crate::wire::encode_bytes(br#"{"receipt_id":"r","stages":[ ]}"#); + assert!(forged.verify(&layer_bytes).is_err()); + // rows drawn from another output + let mut rows = evidence.clone(); + rows.rows_proof = evidence.challenge.proof.clone().unwrap(); + assert!(rows.verify(&layer_bytes).is_err()); + // attention rows without a signature + let mut unsigned = evidence.clone(); + unsigned.rows_signature = None; + assert!(unsigned.verify(&layer_bytes).is_err()); + // attention rows the node did not sign + let mut forged_rows = evidence.clone(); + forged_rows.rows = Some(crate::wire::encode_bytes(b"[]")); + let provenance = forged_rows.verify(&layer_bytes).unwrap(); + let rows = provenance.rows.as_ref().expect("rows"); + assert!(rows.answering(&provenance.binding, &blocks()).is_err()); + // the opening's signature does not sign rows + let mut swapped = evidence.clone(); + swapped.rows = Some(evidence.opening.clone()); + swapped.rows_signature = Some(evidence.opening_signature.clone()); + let provenance = swapped.verify(&layer_bytes).unwrap(); + let rows = provenance.rows.as_ref().expect("rows"); + assert!(rows.answering(&provenance.binding, &blocks()).is_err()); + } +} diff --git a/crates/skippy-receipts/src/ggml_types.rs b/crates/skippy-receipts/src/ggml_types.rs new file mode 100644 index 00000000..d9d91e18 --- /dev/null +++ b/crates/skippy-receipts/src/ggml_types.rs @@ -0,0 +1,98 @@ +//! The ggml tensor types a receipt can name: their ids, their names and +//! how many bytes a block of their values takes. +//! +//! A node names the types of its cache rows in a receipt, and a client +//! reads the types of the claimed GGUF's weights and of the rows a node +//! opens. Both sides take the ids, names and sizes from here, so a name in +//! a receipt means the same type to both. + +/// ggml type ids of the formats [`crate::dequant`] decodes. +pub(crate) const GGML_F32: u32 = 0; +pub(crate) const GGML_F16: u32 = 1; +pub(crate) const GGML_Q4_0: u32 = 2; +pub(crate) const GGML_Q4_1: u32 = 3; +pub(crate) const GGML_Q5_0: u32 = 6; +pub(crate) const GGML_Q5_1: u32 = 7; +pub(crate) const GGML_Q8_0: u32 = 8; +pub(crate) const GGML_Q2_K: u32 = 10; +pub(crate) const GGML_Q3_K: u32 = 11; +pub(crate) const GGML_Q4_K: u32 = 12; +pub(crate) const GGML_Q5_K: u32 = 13; +pub(crate) const GGML_Q6_K: u32 = 14; +pub(crate) const GGML_IQ4_NL: u32 = 20; +pub(crate) const GGML_IQ4_XS: u32 = 23; +pub(crate) const GGML_BF16: u32 = 30; + +/// (values per block, bytes per block) of every ggml type the pinned +/// runtime loads from a GGUF, so a tensor of any of them has a size: the +/// ones the verifier decodes ([`crate::dequant::supports`]) and the rest, +/// by their ggml type id. A type id that is not here was removed from ggml +/// or is unknown to it, and the runtime refuses the file. +pub(crate) fn type_layout(t: u32) -> Option<(u64, u64)> { + Some(match t { + GGML_F32 => (1, 4), + GGML_F16 => (1, 2), + GGML_Q4_0 => (32, 18), + GGML_Q4_1 => (32, 20), + GGML_Q5_0 => (32, 22), + GGML_Q5_1 => (32, 24), + GGML_Q8_0 => (32, 34), + GGML_Q2_K => (256, 84), + GGML_Q3_K => (256, 110), + GGML_Q4_K => (256, 144), + GGML_Q5_K => (256, 176), + GGML_Q6_K => (256, 210), + GGML_IQ4_NL => (32, 18), + GGML_IQ4_XS => (256, 136), + GGML_BF16 => (1, 2), + // q8_1, q8_K + 9 => (32, 36), + 15 => (256, 292), + // iq2_xxs, iq2_xs, iq3_xxs, iq1_s, iq3_s, iq2_s, iq1_m + 16 => (256, 66), + 17 => (256, 74), + 18 => (256, 98), + 19 => (256, 50), + 21 => (256, 110), + 22 => (256, 82), + 29 => (256, 56), + // i8, i16, i32, i64, f64 + 24 => (1, 1), + 25 => (1, 2), + 26 => (1, 4), + 27 | 28 => (1, 8), + // tq1_0, tq2_0 + 34 => (256, 54), + 35 => (256, 66), + // mxfp4, nvfp4, q1_0, q2_0, f8_e4m3 + 39 => (32, 17), + 40 => (64, 36), + 41 => (128, 18), + 42 => (64, 18), + 43 => (1, 1), + _ => return None, + }) +} + +/// How a receipt names the type with id `t`. An id without a name of its +/// own is named by its number. +pub(crate) fn type_name(t: u32) -> String { + match t { + GGML_F32 => "f32".into(), + GGML_F16 => "f16".into(), + GGML_Q4_0 => "q4_0".into(), + GGML_Q4_1 => "q4_1".into(), + GGML_Q5_0 => "q5_0".into(), + GGML_Q5_1 => "q5_1".into(), + GGML_Q8_0 => "q8_0".into(), + GGML_Q2_K => "q2_K".into(), + GGML_Q3_K => "q3_K".into(), + GGML_Q4_K => "q4_K".into(), + GGML_Q5_K => "q5_K".into(), + GGML_Q6_K => "q6_K".into(), + GGML_IQ4_NL => "iq4_nl".into(), + GGML_IQ4_XS => "iq4_xs".into(), + GGML_BF16 => "bf16".into(), + _ => format!("type{t}"), + } +} diff --git a/crates/skippy-receipts/src/glue.rs b/crates/skippy-receipts/src/glue.rs new file mode 100644 index 00000000..e54bbc36 --- /dev/null +++ b/crates/skippy-receipts/src/glue.rs @@ -0,0 +1,684 @@ +//! Client-side checks that bind an opening's matmuls to the committed +//! residual stream and token-mixing values. +//! +//! A replay recomputes the challenged layer, so its matmul columns pass the +//! row checks no matter which weights served the turn. The glue check ties +//! them to the committed values instead. The auditor computes the layer +//! itself, with its own llama.cpp and the claimed GGUF, on the opened +//! values: every weight matmul output, token-mixing output and selection is +//! the opened value, so no large weight is read. Everything between them +//! (norms, RoPE, activations, routing, residual adds) is the auditor's own +//! computation, which it compares with the opened matmul inputs, expert +//! ids, mixing inputs, stored KV rows and the residual leaving the layer +//! (see `docs/design/RECEIPTS_GLUE.md`). No code here names an +//! architecture or a tensor. + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Instant; + +use anyhow::{Context, Result}; + +use crate::attention::AttentionDescriptor; +use crate::cache_types; +use crate::error_bound::{exceeds, worst, worst_of}; +use crate::layer_tensors::TensorKind; +use crate::node_fault::{BlameNode, NodeFault, ensure_node}; +use crate::wire::{AnchorOpening, LayerOpening, LeafOpening, MixingKind, TensorOpening}; + +mod plan; + +pub use plan::PlannedMatmul; + +/// A glue comparison fails above this error, relative to the largest value +/// of the auditor's vector. +pub(crate) const GLUE_TOLERANCE: f64 = 1e-4; +/// Rotary embeddings turn a value by an angle of up to its position in +/// radians, and backends compute the angle in f32. The turned value is then +/// off by up to about the angle's rounding, relative to its magnitude, so +/// the token-mixing values a layer can rotate (mixing inputs and stored rows, +/// such as Q and K; the check does not know which are rotated) get this much +/// more tolerance per position: 0.008 at position 32,768. +pub(crate) const ROTATION_TOLERANCE_PER_POSITION: f64 = 2.0 * f32::EPSILON as f64; +/// A stored row passes within this multiple of the auditor's own rounding +/// error into the cache type (plus [`GLUE_TOLERANCE`] of the row's norm). +pub(crate) const STORED_ROUNDING_FACTOR: f64 = 1.5; + +/// Values of a tensor, column after column. +#[derive(Clone, Debug, PartialEq)] +pub enum GlueValues { + F32(Vec), + I32(Vec), +} + +impl GlueValues { + fn len(&self) -> usize { + match self { + Self::F32(v) => v.len(), + Self::I32(v) => v.len(), + } + } +} + +/// An opened value the evaluation uses instead of computing it. +#[derive(Clone, Debug, PartialEq)] +pub struct GlueInput { + /// `MatmulOutput`, `MixingOutput` or `Selection`. + pub kind: TensorKind, + pub index: u32, + /// Values per column. + pub len: usize, + pub values: GlueValues, +} + +/// One layer at the opened positions, one column per position. +#[derive(Clone, Debug, PartialEq)] +pub struct GlueRequest { + pub layer: u32, + pub positions: Vec, + /// Residual stream entering the layer, column after column. + pub residual: Vec, + pub inputs: Vec, +} + +/// A tensor the evaluation computed, one column per position. +#[derive(Clone, Debug, PartialEq)] +pub struct GlueTensor { + pub layer: u32, + pub kind: TensorKind, + pub index: u32, + pub flags: i32, + /// The weight's name for a matmul input, else the graph node's name. + pub name: String, + /// Values per column. + pub len: usize, + pub values: GlueValues, +} + +impl GlueTensor { + pub(crate) fn f32_column(&self, col: usize) -> Option<&[f32]> { + match &self.values { + GlueValues::F32(v) => v.get(col * self.len..(col + 1) * self.len), + GlueValues::I32(_) => None, + } + } + + fn i32_column(&self, col: usize) -> Option<&[i32]> { + match &self.values { + GlueValues::I32(v) => v.get(col * self.len..(col + 1) * self.len), + GlueValues::F32(_) => None, + } + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GlueOutput { + pub tensors: Vec, + /// Weights read inside token-mixing regions, which no check covers. + pub unchecked_weights: Vec, + /// The layer's attention ops, as the auditor's graph describes them. + pub attention: Vec, +} + +/// How far a stored KV row is from the row the auditor computed (L2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StoredRowError { + pub stored: f64, + /// The computed row's distance from its own round trip through the cache type. + pub rounding: f64, + pub norm: f64, +} + +/// Computes one layer on opened values; implemented over libllama. +pub trait GlueEvaluator { + fn evaluate(&self, request: &GlueRequest) -> Result; + /// Computes the recurrent token mixing of one layer from the opened + /// inputs at consecutive positions of one sequence and the opened + /// states before the first (`MixingState`, one column). Reports the + /// `MixingOutput` values and the `MixingStateOut` states left. + fn evaluate_region(&self, request: &GlueRequest) -> Result; + /// The residual entering layer 0 for each token at its position, column + /// after column, computed from the tokens alone. Only an evaluator of + /// layer 0 can compute it. + fn entry(&self, tokens: &[i32], positions: &[i32]) -> Result>; + /// Compares a stored row in `ggml_type` with a computed f32 row. + fn stored_row_error( + &self, + ggml_type: i32, + stored: &[u8], + computed: &[f32], + ) -> Result; +} + +#[derive(Clone, Debug, PartialEq)] +pub struct GlueVerdict { + pub check: String, + /// Comparisons made, one per position (and tensor). + pub tokens: usize, + pub failing_tokens: usize, + pub max_error: f64, + /// The tensor with the largest error, or what was inconsistent. + pub worst: String, + /// The first failing comparisons, with their errors. + pub failures: Vec, + pub pass: bool, +} + +/// Failing comparisons a verdict lists, at most. +const LISTED_FAILURES: usize = 8; + +#[derive(Clone, Debug, PartialEq)] +pub struct GlueReport { + pub verdicts: Vec, + pub unchecked_weights: Vec, + /// The layer's attention ops, as the auditor's graph describes them. + pub attention: Vec, + /// The layer's weight matmuls by index, as the auditor's graph has + /// them: which weight each reads, and whether it is a router. The row + /// check takes these, never the node's word. + pub matmuls: BTreeMap, + /// Recurrent states the layer's token mixing reads, as the auditor's + /// graph has them: a layer with any is checked by its region. + pub states: usize, + /// Wall time of the auditor's layer evaluation. + pub eval_seconds: f64, + pub pass: bool, +} + +/// Largest difference, relative to the largest reference value. Infinite +/// when a value on either side is not a number. +pub(crate) fn relative_error(actual: &[f32], reference: &[f32]) -> f64 { + if actual.len() != reference.len() { + return f64::INFINITY; + } + let scale = worst_of(reference.iter().map(|&v| f64::from(v).abs())); + let diff = worst_of( + actual + .iter() + .zip(reference) + .map(|(&a, &r)| (f64::from(a) - f64::from(r)).abs()), + ); + if !diff.is_finite() || !scale.is_finite() { + return f64::INFINITY; + } + if scale == 0.0 { + return if diff == 0.0 { 0.0 } else { f64::INFINITY }; + } + diff / scale +} + +/// How far a selection is from a valid pick on the auditor's scores, +/// relative to the largest score: 0 when valid. +/// +/// A full permutation (`argsort`) must be ordered by score, in either +/// direction. A shorter pick (top-k) must hold the highest scores. Scores +/// within the tolerance of each other count as ties, so either choice of a +/// real tie passes. +pub(crate) fn selection_error(ids: &[i32], scores: &[f32]) -> f64 { + let n = scores.len(); + let mut seen = BTreeSet::new(); + let mut picked = Vec::with_capacity(ids.len()); + for &id in ids { + match usize::try_from(id) { + Ok(i) if i < n && seen.insert(i) => picked.push(f64::from(scores[i])), + _ => return f64::INFINITY, + } + } + let scale = worst_of(scores.iter().map(|&v| f64::from(v).abs())); + if scale == 0.0 || !scale.is_finite() { + return if scale == 0.0 { 0.0 } else { f64::INFINITY }; + } + let violation = if picked.len() == n { + let descending = picked.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max); + let ascending = picked.windows(2).map(|w| w[0] - w[1]).fold(0.0, f64::max); + descending.min(ascending) + } else { + let lowest_picked = picked.iter().copied().fold(f64::INFINITY, f64::min); + let highest_left = (0..n) + .filter(|i| !seen.contains(i)) + .map(|i| f64::from(scores[i])) + .fold(f64::NEG_INFINITY, f64::max); + (highest_left - lowest_picked).max(0.0) + }; + violation / scale +} + +/// The stored-row rule: the opened row may be no further from the +/// auditor's value than the auditor's own rounding into the cache type +/// allows. Returns the excess over that bound, relative to the row's norm. +pub(crate) fn stored_excess(error: &StoredRowError) -> f64 { + let bound = STORED_ROUNDING_FACTOR * error.rounding; + // `(NaN).max(0.0)` is 0: a distance that is not a number must not pass + if !(error.stored.is_finite() && error.rounding.is_finite() && error.norm.is_finite()) { + return f64::INFINITY; + } + if error.norm == 0.0 { + return if error.stored <= bound { + 0.0 + } else { + f64::INFINITY + }; + } + (error.stored - bound).max(0.0) / error.norm +} + +/// Builds the evaluation request: the opened residual, and every opened +/// matmul output, mixing output and selection. A value the layer kept no +/// row for at some position is zero there; nothing is compared at it. +/// +/// An error is the node's fault: the request is made of the opening alone. +pub fn glue_request(opening: &LayerOpening) -> Result { + opened_request(opening).or_node_fault() +} + +fn opened_request(opening: &LayerOpening) -> Result { + let leaves = &opening.leaves; + let positions = leaves + .iter() + .map(|l| i32::try_from(l.position)) + .collect::, _>>()?; + let mut residual = Vec::new(); + for leaf in leaves { + residual.extend(leaf.residual_in_values()?); + } + let mut columns: BTreeMap<(TensorKind, u32), Vec>> = BTreeMap::new(); + for (col, leaf) in leaves.iter().enumerate() { + for (key, values) in opened_inputs(leaf)? { + columns + .entry(key) + .or_insert_with(|| vec![None; leaves.len()])[col] = values; + } + } + let inputs = columns + .into_iter() + .map(|((kind, index), cols)| { + let len = cols.iter().flatten().map(GlueValues::len).next(); + join_columns(kind, index, len.unwrap_or(0), cols) + }) + .collect::>()?; + Ok(GlueRequest { + layer: opening.layer, + positions, + residual, + inputs, + }) +} + +type OpenedInputs = Vec<((TensorKind, u32), Option)>; + +fn opened_inputs(leaf: &LeafOpening) -> Result { + let mut out = Vec::new(); + for m in &leaf.matrices { + let values = GlueValues::F32(m.output_values()?); + out.push(((TensorKind::MatmulOutput, m.index), Some(values))); + } + for t in leaf.mixing.iter().filter(|t| t.kind == MixingKind::Output) { + let values = t.f32_values()?.map(GlueValues::F32); + out.push(((TensorKind::MixingOutput, t.index), values)); + } + for s in &leaf.selections { + let values = GlueValues::I32(s.ids.clone()); + out.push(((TensorKind::Selection, s.index), Some(values))); + } + Ok(out) +} + +fn join_columns( + kind: TensorKind, + index: u32, + len: usize, + cols: Vec>, +) -> Result { + let mismatch = || anyhow::anyhow!("opened {} {index} changes length", kind.name()); + let values = if kind == TensorKind::Selection { + let mut all = Vec::with_capacity(len * cols.len()); + for col in cols { + match col { + Some(GlueValues::I32(v)) if v.len() == len => all.extend(v), + None => all.extend(std::iter::repeat_n(0, len)), + _ => return Err(mismatch()), + } + } + GlueValues::I32(all) + } else { + let mut all = Vec::with_capacity(len * cols.len()); + for col in cols { + match col { + Some(GlueValues::F32(v)) if v.len() == len => all.extend(v), + None => all.extend(std::iter::repeat_n(0.0, len)), + _ => return Err(mismatch()), + } + } + GlueValues::F32(all) + }; + Ok(GlueInput { + kind, + index, + len, + values, + }) +} + +/// Collects comparisons into verdicts by check name. +#[derive(Default)] +pub(crate) struct Verdicts(pub(crate) Vec); + +impl Verdicts { + pub(crate) fn add(&mut self, check: &str, what: &str, error: f64) { + self.add_within(check, what, error, GLUE_TOLERANCE); + } + + /// [`Self::add`] with its own tolerance. + pub(crate) fn add_within(&mut self, check: &str, what: &str, error: f64, tolerance: f64) { + let index = match self.0.iter().position(|v| v.check == check) { + Some(index) => index, + None => { + self.0.push(GlueVerdict { + check: check.to_owned(), + tokens: 0, + failing_tokens: 0, + max_error: 0.0, + worst: String::new(), + failures: Vec::new(), + pass: true, + }); + self.0.len() - 1 + } + }; + let verdict = &mut self.0[index]; + verdict.tokens += 1; + // an error that is not a number is the worst there is + let error = worst(error, 0.0); + if error > verdict.max_error || verdict.worst.is_empty() { + verdict.max_error = worst(verdict.max_error, error); + verdict.worst = what.to_owned(); + } + if exceeds(error, tolerance) { + verdict.failing_tokens += 1; + verdict.pass = false; + if verdict.failures.len() < LISTED_FAILURES { + verdict.failures.push(format!("{what} ({error:.1e})")); + } + } + } + + pub(crate) fn inconsistent(&mut self, what: String) { + self.add("layer plan", &what, f64::INFINITY); + } +} + +/// The auditor's tensors by kind and index. +pub(crate) struct Computed<'a>(BTreeMap<(TensorKind, u32), &'a GlueTensor>); + +impl<'a> Computed<'a> { + pub(crate) fn new(output: &'a GlueOutput, layer: u32) -> Self { + Self( + output + .tensors + .iter() + .filter(|t| { + // the residual reported is the one leaving the layer + if t.kind == TensorKind::Residual { + t.layer == layer + 1 + } else { + t.layer == layer + } + }) + .map(|t| ((t.kind, t.index), t)) + .collect(), + ) + } + + pub(crate) fn get(&self, kind: TensorKind, index: u32) -> Option<&'a GlueTensor> { + self.0.get(&(kind, index)).copied() + } + + pub(crate) fn count(&self, kind: TensorKind) -> usize { + self.indices(kind).count() + } + + fn indices(&self, kind: TensorKind) -> impl Iterator + '_ { + self.0 + .keys() + .filter(move |(k, _)| *k == kind) + .map(|(_, index)| *index) + } +} + +/// Phrases of the native evaluator's refusals of a request's values: a +/// value no node of the layer takes, a mixing output left out, a value of +/// another length or type, a selected id out of range, a position the +/// model has no row for. The values come from the opening, so a refusal +/// that names one is the node's fault. Any other error stays the +/// auditor's (see [`crate::node_fault`]). +const REFUSED_VALUE: [&str; 7] = [ + "matches nothing in the layer", + "no opened value for", + "the opened value for", + "the opened selection for", + "has a kind, index, length or type the evaluation does not take", + "is not a position of the model", + "a region's positions must be consecutive", +]; + +/// `error` of an evaluation of opened values, blamed on the node when the +/// evaluator refused one of them, else on the auditor (`what` it could not +/// compute). +pub(crate) fn blame_refused_values(error: anyhow::Error, what: &str) -> anyhow::Error { + let message = format!("{error:#}"); + if REFUSED_VALUE.iter().any(|phrase| message.contains(phrase)) { + return NodeFault::error(format!( + "the auditor's {what} refuses an opened value: {message}" + )); + } + error.context(format!("the auditor cannot compute the {what}")) +} + +/// The request with the values the node committed to alone: the residual +/// and the token-mixing outputs. Matmul outputs and selections are in no +/// leaf, so the node chooses them after it sees the challenge; the +/// evaluator computes them as zeros here. +fn committed_request(request: &GlueRequest) -> GlueRequest { + GlueRequest { + inputs: request + .inputs + .iter() + .filter(|input| input.kind == TensorKind::MixingOutput) + .cloned() + .collect(), + ..request.clone() + } +} + +/// Evaluates the challenged layer on the opening and compares. +/// +/// The layer is evaluated twice. First on the committed values alone, +/// which gives the auditor's plan of the layer before any value the node +/// chose after the challenge reaches the evaluator; the opening must fit +/// that plan. Then on every opened value. Once the committed values +/// evaluate, an evaluation the opening's other values stop fails the +/// layer: the same layer took everything else. So a node cannot turn a +/// failing layer into one the auditor could not compute. Both failures +/// keep the plan, so the row check still reads it. +/// +/// An error that blames the node ([`crate::node_fault::NodeFault`]) is a +/// defect of the opening. Any other error is the auditor's: it could not +/// compute the layer. +pub fn check_glue(evaluator: &dyn GlueEvaluator, opening: &LayerOpening) -> Result { + ensure_node!( + !opening.leaves.is_empty(), + "the opening has no positions to check" + ); + let request = glue_request(opening)?; + let planned = evaluator + .evaluate(&committed_request(&request)) + .map_err(|error| blame_refused_values(error, "challenged layer"))?; + let mut verdicts = Verdicts::default(); + plan::check( + opening, + &Computed::new(&planned, opening.layer), + &mut verdicts, + ); + if verdicts.0.iter().any(|v| !v.pass) { + // the evaluation would take values the layer does not have + return Ok(report(verdicts, planned, opening.layer, 0.0)); + } + let started = Instant::now(); + let output = match evaluator.evaluate(&request) { + Ok(output) => output, + Err(error) => { + verdicts.inconsistent(format!( + "the layer computes the committed values and refuses the matmul outputs or \ + selections opened with them: {error:#}" + )); + return Ok(report(verdicts, planned, opening.layer, 0.0)); + } + }; + let eval_seconds = started.elapsed().as_secs_f64(); + let computed = Computed::new(&output, opening.layer); + for (col, leaf) in opening.leaves.iter().enumerate() { + compare_position(evaluator, leaf, col, &computed, &mut verdicts)?; + } + Ok(report(verdicts, output, opening.layer, eval_seconds)) +} + +fn report(verdicts: Verdicts, output: GlueOutput, layer: u32, eval_seconds: f64) -> GlueReport { + let computed = Computed::new(&output, layer); + let states = computed.count(TensorKind::MixingState); + let matmuls = plan::matmuls(&computed); + let pass = verdicts.0.iter().all(|v| v.pass); + GlueReport { + verdicts: verdicts.0, + unchecked_weights: output.unchecked_weights, + attention: output.attention, + matmuls, + states, + eval_seconds, + pass, + } +} + +/// The auditor's own row for a stored value, compared with the opened one. +fn stored_error( + evaluator: &dyn GlueEvaluator, + opened: &TensorOpening, + reference: &[f32], +) -> Result { + let Ok(Some(stored)) = opened.bytes() else { + return Ok(f64::INFINITY); + }; + // the evaluator reads as many bytes as the type packs the auditor's row + // into: a shorter row must never reach it + let whole = cache_types::decoded(opened.ggml_type) + .and_then(|ggml_type| cache_types::row_bytes(ggml_type, reference.len())); + if whole != Some(stored.len()) { + return Ok(f64::INFINITY); + } + let error = evaluator.stored_row_error(opened.ggml_type, &stored, reference)?; + Ok(stored_excess(&error)) +} + +fn compare_position( + evaluator: &dyn GlueEvaluator, + leaf: &LeafOpening, + col: usize, + computed: &Computed<'_>, + verdicts: &mut Verdicts, +) -> Result<()> { + let at = |what: &str| format!("position {}: {what}", leaf.position); + let rotated = GLUE_TOLERANCE + ROTATION_TOLERANCE_PER_POSITION * f64::from(leaf.position); + for m in &leaf.matrices { + if let Some(t) = computed.get(TensorKind::MatmulInput, m.index) { + let error = t.f32_column(col).map_or(f64::INFINITY, |reference| { + m.input_values() + .map_or(f64::INFINITY, |opened| relative_error(&opened, reference)) + }); + verdicts.add("matmul inputs", &at(&m.weight), error); + } + let ids = computed + .get(TensorKind::ExpertIds, m.index) + .and_then(|t| t.i32_column(col)); + if ids.is_some() || m.experts.is_some() { + let same = ids.is_some() && ids == m.experts.as_deref(); + let error = if same { 0.0 } else { f64::INFINITY }; + verdicts.add("expert ids", &at(&m.weight), error); + } + } + for t in &leaf.mixing { + let kind = t.kind.tensor_kind(); + let what = at(&format!("{} {}", kind.name(), t.index)); + let reference = computed.get(kind, t.index).and_then(|c| c.f32_column(col)); + match (t.kind, reference) { + // the glue takes the outputs, and states belong to the region + (MixingKind::Output | MixingKind::State, _) => {} + (_, None) => verdicts.add(&format!("{}s", kind.name()), &what, f64::INFINITY), + // a value the layer kept no row for is absent; the plan check + // fails one that is absent on a kept row + (_, Some(_)) if t.values.is_none() => {} + (MixingKind::Input, Some(reference)) => { + let error = match t.f32_values() { + Ok(Some(opened)) => relative_error(&opened, reference), + _ => f64::INFINITY, + }; + verdicts.add_within("mixing inputs", &what, error, rotated); + } + (MixingKind::Stored, Some(reference)) => { + let error = stored_error(evaluator, t, reference)?; + verdicts.add_within("stored rows", &what, error, rotated); + } + } + } + for s in &leaf.selections { + let scores = computed + .get(TensorKind::SelectionScores, s.index) + .and_then(|t| t.f32_column(col)); + let error = scores.map_or(f64::INFINITY, |scores| selection_error(&s.ids, scores)); + verdicts.add("selections", &at(&format!("selection {}", s.index)), error); + } + if leaf.residual_out.is_some() { + let reference = computed + .get(TensorKind::Residual, 0) + .and_then(|t| t.f32_column(col)); + let error = match (leaf.residual_out_values(), reference) { + (Ok(Some(opened)), Some(reference)) => relative_error(&opened, reference), + _ => f64::INFINITY, + }; + verdicts.add("residual out", &at("residual leaving the layer"), error); + } + Ok(()) +} + +/// Recomputes the residual entering layer 0 from each anchor's token and +/// compares it with the opened one. This ties the committed residual +/// stream to the tokens of the request. +pub fn check_anchors( + evaluator: &dyn GlueEvaluator, + anchors: &[AnchorOpening], +) -> Result { + let mut verdicts = Verdicts::default(); + if anchors.is_empty() { + verdicts.add("anchors", "no anchor was opened", f64::INFINITY); + return Ok(verdicts.0.remove(0)); + } + let tokens: Vec = anchors.iter().map(|a| a.token).collect(); + let positions = anchors + .iter() + .map(|a| i32::try_from(a.position)) + .collect::, _>>() + .map_err(|_| NodeFault::error("an anchor's position is past any sequence"))?; + let computed = evaluator + .entry(&tokens, &positions) + .context("the auditor cannot compute the input of layer 0")?; + let len = computed.len() / anchors.len(); + for (col, anchor) in anchors.iter().enumerate() { + let what = format!("position {}: token {}", anchor.position, anchor.token); + let error = anchor.residual_values().map_or(f64::INFINITY, |opened| { + relative_error(&opened, &computed[col * len..(col + 1) * len]) + }); + verdicts.add("anchors", &what, error); + } + Ok(verdicts.0.remove(0)) +} + +#[cfg(test)] +#[path = "glue/tests.rs"] +mod tests; diff --git a/crates/skippy-receipts/src/glue/plan.rs b/crates/skippy-receipts/src/glue/plan.rs new file mode 100644 index 00000000..e065cff5 --- /dev/null +++ b/crates/skippy-receipts/src/glue/plan.rs @@ -0,0 +1,181 @@ +//! The opening against the layer the auditor built: its plan. +//! +//! The auditor's evaluation reports the layer's weight matmuls, mixing +//! values and selections by index. An opening must describe that layer and +//! no other: the same matmuls, each once, reading the same weights with +//! the same router flags; the same mixing values; the same selections. A +//! value the auditor does not get it computes as zeros, so a node that +//! left one out would skip the work behind it; and a matmul opened twice +//! would count twice toward the row check's allowance for outliers. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::{Computed, Verdicts}; +use crate::layer_tensors::{FLAG_ROUTER, TensorKind}; +use crate::wire::{LayerOpening, LeafOpening, MixingKind}; + +/// One weight matmul of a layer, as the auditor's graph has it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlannedMatmul { + /// The GGUF tensor the matmul reads. + pub weight: String, + /// Its output feeds a selection, so every row of it is checked. + pub router: bool, +} + +/// The layer's weight matmuls by index. +pub(super) fn matmuls(computed: &Computed<'_>) -> BTreeMap { + computed + .indices(TensorKind::MatmulInput) + .filter_map(|index| { + let tensor = computed.get(TensorKind::MatmulInput, index)?; + let planned = PlannedMatmul { + weight: tensor.name.clone(), + router: tensor.flags & FLAG_ROUTER != 0, + }; + Some((index, planned)) + }) + .collect() +} + +/// Fails the "layer plan" verdict for everything in `opening` that is not +/// the auditor's layer. +pub(super) fn check(opening: &LayerOpening, computed: &Computed<'_>, verdicts: &mut Verdicts) { + let planned = matmuls(computed); + for leaf in &opening.leaves { + check_matmuls(leaf, &planned, verdicts); + check_matmul_shapes(leaf, computed, verdicts); + check_mixing(leaf, computed, verdicts); + check_selections(leaf, computed, verdicts); + } +} + +/// A final layer drops the rows it does not output, with their later +/// matmuls and selections; the committed residual out records which rows +/// those are. +fn kept(leaf: &LeafOpening) -> bool { + leaf.residual_out.is_some() +} + +fn check_matmuls( + leaf: &LeafOpening, + planned: &BTreeMap, + verdicts: &mut Verdicts, +) { + let position = leaf.position; + let mut opened = BTreeSet::new(); + for m in &leaf.matrices { + if !opened.insert(m.index) { + verdicts.inconsistent(format!( + "position {position}: matmul {} ({}) is opened more than once", + m.index, m.weight + )); + } + match planned.get(&m.index) { + None => verdicts.inconsistent(format!( + "position {position}: the layer has no matmul {} ({})", + m.index, m.weight + )), + Some(plan) if plan.weight != m.weight => verdicts.inconsistent(format!( + "position {position}: matmul {} reads {}, opened as {}", + m.index, plan.weight, m.weight + )), + Some(plan) if plan.router != m.router => verdicts.inconsistent(format!( + "position {position}: {} is opened with the wrong router flag", + m.weight + )), + Some(_) => {} + } + } + // a kept row must open every matmul: the auditor computes an unopened + // one as zeros, which would skip its work + if kept(leaf) { + for (index, plan) in planned.iter().filter(|(index, _)| !opened.contains(index)) { + verdicts.inconsistent(format!( + "position {position}: matmul {index} ({}) is not opened", + plan.weight + )); + } + } +} + +/// Each opened matmul has the planned input width, and names as many +/// experts as the layer uses. The opened values have to fit the weight +/// they name ([`crate::audit::check_matmul_shape`]), so the output then has +/// the planned length too; a weight shared across groups would otherwise +/// let a node open more groups than the layer computes. +fn check_matmul_shapes(leaf: &LeafOpening, computed: &Computed<'_>, verdicts: &mut Verdicts) { + let position = leaf.position; + for m in &leaf.matrices { + let Some(input) = computed.get(TensorKind::MatmulInput, m.index) else { + continue; + }; + let opened = m.input_values().map_or(0, |values| values.len()); + if opened != input.len { + verdicts.inconsistent(format!( + "position {position}: {} is opened with {opened} input values, the layer has {}", + m.weight, input.len + )); + } + let used = computed + .get(TensorKind::ExpertIds, m.index) + .map(|ids| ids.len); + let named = m.experts.as_ref().map(Vec::len); + if used != named { + verdicts.inconsistent(format!( + "position {position}: {} names {named:?} experts, the layer uses {used:?}", + m.weight + )); + } + } +} + +fn check_mixing(leaf: &LeafOpening, computed: &Computed<'_>, verdicts: &mut Verdicts) { + let position = leaf.position; + if let Err(error) = crate::binding::check_mixing_order(&leaf.mixing) { + verdicts.inconsistent(format!("position {position}: {error:#}")); + } + for (kind, mixing) in [ + (TensorKind::MixingInput, MixingKind::Input), + (TensorKind::MixingStored, MixingKind::Stored), + (TensorKind::MixingState, MixingKind::State), + ] { + let opened = leaf.mixing.iter().filter(|t| t.kind == mixing).count(); + if opened != computed.count(kind) { + verdicts.inconsistent(format!( + "position {position}: {opened} opened {}s, the layer has {}", + kind.name(), + computed.count(kind) + )); + } + } + if !kept(leaf) { + return; + } + // a row the layer kept has every value its token mixing reads, stores + // and gives; an absent one would go uncompared. A state is opened only + // where a ubatch starts. + let absent = leaf + .mixing + .iter() + .filter(|t| t.kind != MixingKind::State && t.values.is_none()); + for value in absent { + verdicts.inconsistent(format!( + "position {position}: {} {} is absent on a row the layer kept", + value.kind.tensor_kind().name(), + value.index + )); + } +} + +fn check_selections(leaf: &LeafOpening, computed: &Computed<'_>, verdicts: &mut Verdicts) { + let dropped = !kept(leaf) && leaf.selections.is_empty(); + let opened: Vec = leaf.selections.iter().map(|s| s.index).collect(); + let planned: Vec = computed.indices(TensorKind::SelectionScores).collect(); + if opened != planned && !dropped { + verdicts.inconsistent(format!( + "position {}: selections {opened:?} are opened, the layer has {planned:?}", + leaf.position + )); + } +} diff --git a/crates/skippy-receipts/src/glue/tests.rs b/crates/skippy-receipts/src/glue/tests.rs new file mode 100644 index 00000000..98898bc5 --- /dev/null +++ b/crates/skippy-receipts/src/glue/tests.rs @@ -0,0 +1,579 @@ +use anyhow::bail; + +use super::*; +use crate::layer_tensors::{FLAG_ROUTER, GGML_F32}; +use crate::wire::{AnchorOpening, MatrixOpening, SelectionOpening, TensorOpening, encode_f32}; + +/// A toy layer the evaluator computes on opened values: +/// +/// ```text +/// matmul 0 (blk.0.a.weight): input = 2 · residual +/// matmul 1 (blk.0.router.weight): input = residual, a router +/// selection 0: scores = matmul 1 output +/// mixing input 0, stored row 0: residual +/// residual out = residual + matmul 0 output + mixing output 0 +/// entry of layer 0 = [token, position] +/// ``` +struct ToyLayer; + +impl ToyLayer { + /// An opened column; like the native evaluator, an unopened value is zeros. + fn column( + request: &GlueRequest, + kind: TensorKind, + index: u32, + col: usize, + len: usize, + ) -> Vec { + let Some(input) = request + .inputs + .iter() + .find(|i| i.kind == kind && i.index == index) + else { + return vec![0.0; len]; + }; + match &input.values { + GlueValues::F32(v) => v[col * input.len..(col + 1) * input.len].to_vec(), + GlueValues::I32(_) => panic!("f32 expected"), + } + } +} + +fn tensor( + kind: TensorKind, + index: u32, + flags: i32, + name: &str, + len: usize, + values: Vec, +) -> GlueTensor { + GlueTensor { + layer: if kind == TensorKind::Residual { 1 } else { 0 }, + kind, + index, + flags, + name: name.into(), + len, + values: GlueValues::F32(values), + } +} + +impl GlueEvaluator for ToyLayer { + fn evaluate(&self, request: &GlueRequest) -> Result { + let n = request.positions.len(); + let len = request.residual.len() / n; + let mut doubled = Vec::new(); + let mut scores = Vec::new(); + let mut out = Vec::new(); + for col in 0..n { + let r = &request.residual[col * len..(col + 1) * len]; + doubled.extend(r.iter().map(|v| v * 2.0)); + scores.extend(Self::column(request, TensorKind::MatmulOutput, 1, col, 3)); + let m = Self::column(request, TensorKind::MatmulOutput, 0, col, len); + let a = Self::column(request, TensorKind::MixingOutput, 0, col, len); + out.extend((0..len).map(|i| r[i] + m[i] + a[i])); + } + let experts = scores.len() / n; + Ok(GlueOutput { + tensors: vec![ + tensor( + TensorKind::MatmulInput, + 0, + 0, + "blk.0.a.weight", + len, + doubled, + ), + tensor( + TensorKind::MatmulInput, + 1, + FLAG_ROUTER, + "blk.0.router.weight", + len, + request.residual.clone(), + ), + tensor( + TensorKind::MixingInput, + 0, + 0, + "q", + len, + request.residual.clone(), + ), + tensor( + TensorKind::MixingStored, + 0, + 0, + "k", + len, + request.residual.clone(), + ), + tensor(TensorKind::SelectionScores, 0, 0, "probs", experts, scores), + tensor(TensorKind::Residual, 0, 0, "l_out", len, out), + ], + unchecked_weights: vec!["blk.0.sinks".into()], + attention: Vec::new(), + }) + } + + fn entry(&self, tokens: &[i32], positions: &[i32]) -> Result> { + Ok(tokens + .iter() + .zip(positions) + .flat_map(|(&t, &p)| [t as f32, p as f32]) + .collect()) + } + + fn evaluate_region(&self, _: &GlueRequest) -> Result { + bail!("the toy layer keeps no recurrent state") + } + + fn stored_row_error( + &self, + ggml_type: i32, + stored: &[u8], + computed: &[f32], + ) -> Result { + // the check never hands over a row of a type it does not know, or + // of fewer bytes than the type packs the computed row into + assert_eq!(ggml_type, GGML_F32); + assert_eq!(stored.len(), computed.len() * 4); + let stored = crate::layer_tensors::decode_f32_bytes(stored); + let l2 = |v: &mut dyn Iterator| v.map(|x| x * x).sum::().sqrt(); + Ok(StoredRowError { + stored: l2(&mut stored.iter().zip(computed).map(|(a, b)| f64::from(a - b))), + rounding: 0.0, + norm: l2(&mut computed.iter().map(|&v| f64::from(v))), + }) + } +} + +fn honest_leaf(position: u32, r: [f32; 2]) -> LeafOpening { + let m = [0.5, -0.25]; + let a = [0.125, 1.0]; + let scores = [0.1f32, 0.9, 0.4]; + let mixing = |kind, values: &[f32]| { + TensorOpening::new( + kind, + 0, + Some((GGML_F32, &crate::layer_tensors::f32_bytes(values))), + ) + }; + LeafOpening { + position, + residual_in: encode_f32(&r), + residual_out: Some(encode_f32(&[r[0] + m[0] + a[0], r[1] + m[1] + a[1]])), + residual_in_path: Vec::new(), + mixing_path: Vec::new(), + residual_out_path: Vec::new(), + mixing: vec![ + mixing(MixingKind::Input, &r), + mixing(MixingKind::Stored, &r), + mixing(MixingKind::Output, &a), + ], + matrices: vec![ + MatrixOpening { + index: 0, + weight: "blk.0.a.weight".into(), + router: false, + experts: None, + input: encode_f32(&[r[0] * 2.0, r[1] * 2.0]), + output: encode_f32(&m), + }, + MatrixOpening { + index: 1, + weight: "blk.0.router.weight".into(), + router: true, + experts: None, + input: encode_f32(&r), + output: encode_f32(&scores), + }, + ], + selections: vec![SelectionOpening { + index: 0, + ids: vec![1, 2], + }], + } +} + +fn opening(leaves: Vec) -> LayerOpening { + LayerOpening { layer: 0, leaves } +} + +fn honest() -> LayerOpening { + opening(vec![ + honest_leaf(3, [1.0, 2.0]), + honest_leaf(4, [-1.0, 0.5]), + ]) +} + +fn failing(report: &GlueReport) -> Vec<&str> { + report + .verdicts + .iter() + .filter(|v| !v.pass) + .map(|v| v.check.as_str()) + .collect() +} + +#[test] +fn an_honest_opening_passes() { + let report = check_glue(&ToyLayer, &honest()).unwrap(); + assert!(report.pass, "{:?}", report.verdicts); + assert_eq!(report.unchecked_weights, vec!["blk.0.sinks".to_string()]); + let checks: Vec<&str> = report.verdicts.iter().map(|v| v.check.as_str()).collect(); + for check in [ + "matmul inputs", + "mixing inputs", + "stored rows", + "selections", + "residual out", + ] { + assert!(checks.contains(&check), "{check} missing from {checks:?}"); + } +} + +#[test] +fn a_changed_matmul_input_fails() { + let mut opening = honest(); + opening.leaves[1].matrices[0].input = encode_f32(&[-2.0, 1.01]); + assert_eq!( + failing(&check_glue(&ToyLayer, &opening).unwrap()), + ["matmul inputs"] + ); +} + +#[test] +fn a_changed_stored_row_fails() { + let mut opening = honest(); + let row = crate::layer_tensors::f32_bytes(&[1.0, 2.001]); + opening.leaves[0].mixing[1] = TensorOpening::new(MixingKind::Stored, 0, Some((GGML_F32, &row))); + assert_eq!( + failing(&check_glue(&ToyLayer, &opening).unwrap()), + ["stored rows"] + ); +} + +#[test] +fn a_steered_selection_fails() { + let mut opening = honest(); + opening.leaves[0].selections[0].ids = vec![1, 0]; + assert_eq!( + failing(&check_glue(&ToyLayer, &opening).unwrap()), + ["selections"] + ); +} + +#[test] +fn a_mislabeled_matmul_fails_the_plan() { + let mut opening = honest(); + opening.leaves[0].matrices[0].weight = "blk.0.b.weight".into(); + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); + let mut opening = honest(); + opening.leaves[0].matrices[1].router = false; + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); +} + +#[test] +fn a_missing_mixing_value_fails_the_plan() { + let mut opening = honest(); + opening.leaves[1].mixing.remove(1); + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); +} + +#[test] +fn a_matmul_opened_twice_fails_the_plan() { + // copies of an honest column would pad the row check's allowance + let mut opening = honest(); + let copy = opening.leaves[0].matrices[0].clone(); + opening.leaves[0].matrices.push(copy); + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert_eq!(failing(&report), ["layer plan"], "{:?}", report.verdicts); +} + +#[test] +fn a_selection_the_layer_does_not_have_fails_the_plan() { + let mut opening = honest(); + opening.leaves[0].selections.push(SelectionOpening { + index: 1, + ids: vec![0], + }); + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); + // nor may the one it has go by another index + let mut opening = honest(); + opening.leaves[0].selections[0].index = 1; + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); +} + +#[test] +fn a_value_absent_on_a_kept_row_fails_the_plan() { + // an absent value is not compared, so a kept row may not leave one out + for index in 0..3 { + let mut opening = honest(); + let value = &mut opening.leaves[1].mixing[index]; + *value = TensorOpening::new(value.kind, 0, None); + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert!( + failing(&report).contains(&"layer plan"), + "mixing value {index}: {:?}", + report.verdicts + ); + } +} + +#[test] +fn the_plan_is_the_auditors_and_names_the_routers() { + // the node clears every router flag; the report still says which are + let mut opening = honest(); + for leaf in &mut opening.leaves { + leaf.matrices[1].router = false; + } + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert_eq!(failing(&report), ["layer plan"]); + let plan: Vec<(u32, &str, bool)> = report + .matmuls + .iter() + .map(|(index, m)| (*index, m.weight.as_str(), m.router)) + .collect(); + assert_eq!( + plan, + [ + (0, "blk.0.a.weight", false), + (1, "blk.0.router.weight", true) + ] + ); +} + +#[test] +fn a_value_that_is_not_a_number_fails_its_comparison() { + type Change = fn(&mut LeafOpening); + let nan = f32::NAN; + let changes: [(&str, Change); 5] = [ + ("matmul inputs", |leaf| { + leaf.matrices[0].input = encode_f32(&[f32::NAN, 4.0]); + }), + ("matmul inputs", |leaf| { + leaf.matrices[0].input = encode_f32(&[f32::INFINITY, 4.0]); + }), + ("mixing inputs", |leaf| { + let bytes = crate::layer_tensors::f32_bytes(&[1.0, f32::NAN]); + leaf.mixing[0] = TensorOpening::new(MixingKind::Input, 0, Some((GGML_F32, &bytes))); + }), + ("stored rows", |leaf| { + let bytes = crate::layer_tensors::f32_bytes(&[f32::NAN, 2.0]); + leaf.mixing[1] = TensorOpening::new(MixingKind::Stored, 0, Some((GGML_F32, &bytes))); + }), + ("residual out", |leaf| { + leaf.residual_out = Some(encode_f32(&[f32::NAN, f32::NAN])); + }), + ]; + for (check, change) in changes { + let mut opening = honest(); + change(&mut opening.leaves[0]); + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert!(!report.pass, "{check}"); + assert!(failing(&report).contains(&check), "{check}: {report:?}"); + } + // the comparisons themselves, which `f64::max` used to let through + assert_eq!(relative_error(&[nan, 1.0], &[1.0, 1.0]), f64::INFINITY); + assert_eq!(relative_error(&[1.0, 1.0], &[nan, 1.0]), f64::INFINITY); + assert_eq!(selection_error(&[0], &[nan, 1.0]), f64::INFINITY); + let distance = |stored, rounding, norm| StoredRowError { + stored, + rounding, + norm, + }; + for error in [ + distance(f64::NAN, 0.01, 10.0), + distance(0.01, f64::NAN, 10.0), + distance(0.01, 0.01, f64::NAN), + ] { + assert_eq!(stored_excess(&error), f64::INFINITY, "{error:?}"); + } + let mut verdicts = Verdicts::default(); + verdicts.add("check", "a value", f64::NAN); + assert!(!verdicts.0[0].pass); + assert_eq!(verdicts.0[0].max_error, f64::INFINITY); +} + +#[test] +fn a_stored_row_of_another_type_or_length_never_reaches_the_evaluator() { + // the toy evaluator panics on either, as the native one may read past + // the row + let short = crate::layer_tensors::f32_bytes(&[1.0]); + let whole = crate::layer_tensors::f32_bytes(&[1.0, 2.0]); + for (ggml_type, bytes) in [(GGML_F32, &short), (39, &whole), (-1, &whole), (3, &whole)] { + let mut opening = honest(); + opening.leaves[0].mixing[1] = + TensorOpening::new(MixingKind::Stored, 0, Some((ggml_type, bytes))); + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert_eq!(failing(&report), ["stored rows"], "type {ggml_type}"); + } +} + +#[test] +fn an_opening_that_makes_no_request_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + let empty = check_glue(&ToyLayer, &opening(Vec::new())).unwrap_err(); + assert!(NodeFault::find(&empty).is_some(), "{empty:#}"); + // a matmul output that changes length between positions + let mut ragged = honest(); + ragged.leaves[1].matrices[0].output = encode_f32(&[0.5]); + let error = check_glue(&ToyLayer, &ragged).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + let mut undecodable = honest(); + undecodable.leaves[0].residual_in = "not base64".into(); + let error = check_glue(&ToyLayer, &undecodable).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} + +/// An evaluator that cannot compute the layer, as one whose claimed GGUF +/// is out of reach. +struct Unavailable; + +impl GlueEvaluator for Unavailable { + fn evaluate(&self, _: &GlueRequest) -> Result { + bail!("the layer did not load") + } + + fn evaluate_region(&self, _: &GlueRequest) -> Result { + bail!("the layer did not load") + } + + fn entry(&self, _: &[i32], _: &[i32]) -> Result> { + bail!("the layer did not load") + } + + fn stored_row_error(&self, _: i32, _: &[u8], _: &[f32]) -> Result { + bail!("the layer did not load") + } +} + +#[test] +fn an_evaluator_that_cannot_run_blames_nobody() { + use crate::node_fault::NodeFault; + let error = check_glue(&Unavailable, &honest()).unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); + let anchors = [anchor(3, 7, [7.0, 3.0])]; + let error = check_anchors(&Unavailable, &anchors).unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} + +#[test] +fn a_changed_residual_out_fails() { + let mut opening = honest(); + opening.leaves[1].residual_out = Some(encode_f32(&[-0.375, 1.3])); + assert_eq!( + failing(&check_glue(&ToyLayer, &opening).unwrap()), + ["residual out"] + ); +} + +#[test] +fn absent_rows_are_zero_and_not_compared() { + let mut opening = honest(); + opening.leaves[1].residual_out = None; + let request = glue_request(&opening).unwrap(); + assert_eq!(request.positions, vec![3, 4]); + assert_eq!(request.residual, vec![1.0, 2.0, -1.0, 0.5]); + let selection = request + .inputs + .iter() + .find(|i| i.kind == TensorKind::Selection) + .unwrap(); + assert_eq!(selection.values, GlueValues::I32(vec![1, 2, 1, 2])); + assert!(check_glue(&ToyLayer, &opening).unwrap().pass); +} + +#[test] +fn a_dropped_row_opens_no_selection() { + let mut opening = honest(); + let leaf = &mut opening.leaves[1]; + leaf.residual_out = None; + leaf.matrices.retain(|m| !m.router); + leaf.selections.clear(); + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert!(report.pass, "{:?}", report.verdicts); + // a row that is kept must open its selections + let mut opening = honest(); + opening.leaves[1].selections.clear(); + assert!(failing(&check_glue(&ToyLayer, &opening).unwrap()).contains(&"layer plan")); +} + +#[test] +fn selections_accept_real_ties_only() { + let scores = [0.5, 0.2, 0.5 - 1e-6, 0.1]; + assert_eq!(selection_error(&[0, 2], &scores), 0.0); + assert!(selection_error(&[2, 0], &scores) <= GLUE_TOLERANCE); + assert!(selection_error(&[0, 1], &scores) > GLUE_TOLERANCE); + // a full argsort, in either direction + assert_eq!(selection_error(&[0, 2, 1, 3], &scores), 0.0); + assert_eq!(selection_error(&[3, 1, 2, 0], &scores), 0.0); + assert!(selection_error(&[0, 1, 2, 3], &scores) > GLUE_TOLERANCE); + // repeated or out-of-range ids + assert!(selection_error(&[0, 0], &scores).is_infinite()); + assert!(selection_error(&[4], &scores).is_infinite()); +} + +#[test] +fn stored_rows_may_round_like_the_auditor() { + let error = |stored, rounding| StoredRowError { + stored, + rounding, + norm: 10.0, + }; + assert_eq!(stored_excess(&error(0.015, 0.01)), 0.0); + assert!(stored_excess(&error(0.0155, 0.01)) > 0.0); + assert!(stored_excess(&error(0.0155, 0.01)) <= GLUE_TOLERANCE); + assert!(stored_excess(&error(0.05, 0.01)) > GLUE_TOLERANCE); +} + +#[test] +fn rotated_values_get_more_tolerance_further_out() { + // Q at position 2319 off by its f32 angle rounding, as measured on CUDA + let rotated = + |position: u32| GLUE_TOLERANCE + ROTATION_TOLERANCE_PER_POSITION * f64::from(position); + let mut verdicts = Verdicts::default(); + verdicts.add_within("mixing inputs", "position 2319", 1.8e-4, rotated(2319)); + assert!(verdicts.0[0].pass); + verdicts.add_within("mixing inputs", "position 10", 1.8e-4, rotated(10)); + assert!(!verdicts.0[0].pass); + assert_eq!(verdicts.0[0].failing_tokens, 1); + // still tight next to the values: 0.8% at 32k + assert!(rotated(32_768) < 0.01); +} + +#[test] +fn an_unopened_matmul_fails_the_plan() { + // The node skips matmul 0 and commits the residual out it gives as + // zeros; the auditor's own computation agrees, so only the plan catches it. + let mut opening = honest(); + for leaf in &mut opening.leaves { + let r = leaf.residual_in_values().unwrap(); + leaf.matrices.retain(|m| m.index != 0); + leaf.residual_out = Some(encode_f32(&[r[0] + 0.125, r[1] + 1.0])); + } + let report = check_glue(&ToyLayer, &opening).unwrap(); + assert_eq!(failing(&report), ["layer plan"], "{:?}", report.verdicts); +} + +fn anchor(position: u32, token: i32, residual: [f32; 2]) -> AnchorOpening { + AnchorOpening { + position, + token, + residual: encode_f32(&residual), + path: Vec::new(), + } +} + +#[test] +fn anchors_must_be_the_input_their_tokens_make() { + let honest = [anchor(3, 7, [7.0, 3.0]), anchor(5, 9, [9.0, 5.0])]; + assert!(check_anchors(&ToyLayer, &honest).unwrap().pass); + // the input of another token under this token's name + let swapped = [anchor(3, 7, [7.0, 3.0]), anchor(5, 9, [8.0, 5.0])]; + let verdict = check_anchors(&ToyLayer, &swapped).unwrap(); + assert!(!verdict.pass); + assert_eq!(verdict.failing_tokens, 1); + assert!(!check_anchors(&ToyLayer, &[]).unwrap().pass); +} diff --git a/crates/skippy-receipts/src/head.rs b/crates/skippy-receipts/src/head.rs new file mode 100644 index 00000000..a5a24499 --- /dev/null +++ b/crates/skippy-receipts/src/head.rs @@ -0,0 +1,920 @@ +//! The output hea check. The final stage opens the residual leaving the +//! model's final layer at each head position, and the logits it computed +//! from it ([`crate::wire::HeadOpening`]). The client checks those logits +//! against the output norm and the output matrix of the claimed GGUF, with +//! the rounding of the node's backend, and then checks on them that the +//! token the turn sampled from that position is the greedy choice, or for +//! a sampled turn one its filters keep ([`sampling`]) and, when the turn's +//! draw can be replayed, the one the draw picks ([`draw`]). A token that +//! the turn's reasoning budget forced must be the forced one +//! ([`reasoning_budget`]). +//! +//! Without this check a node could run every claimed layer and still pick +//! other tokens. The residual is committed and chained to the checked +//! layers, so the node cannot change it either. +//! +//! The logits are checked in one of two ways, which accept the same +//! logits and judge the token on the same values, so they give one +//! verdict. An audit holds a secret head key and reads a few rows of the +//! matrix ([`key`]). A recheck of evidence has no key and reads every row +//! ([`every_row`]). Judging the token on the node's own logits matters: a +//! client that computed them without the node's activation rounding would +//! be off by more than a near-tie, and would refuse an honest node. +//! +//! A token whose logit is within [`TIE_BAND`] of the best one is accepted, +//! and counted: a node can steer near-ties inside the band, so a turn with +//! more of them than chance allows is flagged. +//! +//! A model that soft-caps its logits opens logits that are not the +//! matrix's product, so no check here can tell the node's logits from +//! others. Logits the client computes itself lack the node's activation +//! rounding, by more than the tie band, so judging a token on them could +//! fail an honest node. Such a model's tokens are not judged +//! ([`token_rule_for`]); [`check_computed_head`] still checks that its +//! final residuals fit the head. + +use anyhow::{Context, Result, bail}; + +use crate::node_fault::{BlameNode, ensure_node, node_fault}; +use crate::weights::{MetaValue, WeightFile}; +use crate::wire::{HeadOpening, Receipt}; + +pub mod draw; +pub mod every_row; +pub mod key; +pub mod opened_logits; +pub mod reasoning_budget; +pub mod sampling; + +use reasoning_budget::Forcing; +use sampling::TokenRule; + +/// The tie band, relative to the root mean square of a position's logits. +/// +/// The token is judged on the logits the node opened, which its replay +/// computed again. Where a replay does not repeat the serving kernel bit +/// for bit, they differ from the logits the node sampled from by that +/// kernel's rounding, and the band leaves room for it. +/// +/// The band does not cover logits the client computes without the node's +/// activation rounding. On CPU with Q8_0 weights those were up to 4e-2 of +/// the RMS from an honest node's over the vocabulary, and about 2e-2 among +/// the likeliest tokens. So no token is judged on such logits +/// ([`token_rule_for`]). +pub(crate) const TIE_BAND: f64 = 1e-2; + +/// The band of a replayed draw, relative to the root mean square of the +/// logits the node opened, which the draw is replayed on. +/// +/// The node drew from its own logits, so the replay follows it exactly up +/// to the last bits of `exp`, which the node's and the client's libraries +/// may round apart. Every honest draw measured was exact with no band: +/// about 130 on CPU, 120 on CUDA (Q8_0 and Q4_K_M), and 160 on Vulkan +/// before it lost its rounding profiles. A wider band would only let a +/// node steer the draws near a boundary. +pub(crate) const DRAW_BAND: f64 = 1e-4; + +fn root_mean_square(logits: &[f64]) -> f64 { + if logits.is_empty() { + return 0.0; + } + (logits.iter().map(|v| v * v).sum::() / logits.len() as f64).sqrt() +} + +/// Tokens accepted within the tie band that a turn of `positions` checked +/// positions may have before it is flagged. +pub(crate) fn allowed_ties(positions: usize) -> usize { + 1 + positions / 16 +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum NormKind { + /// Scales by the root mean square. + Rms, + /// Subtracts the mean and scales by the standard deviation. + Layer, +} + +#[derive(Clone, Debug)] +struct OutputNorm { + kind: NormKind, + eps: f64, + weight: Vec, + bias: Option>, +} + +impl OutputNorm { + /// The norm of an opened residual. A residual of another width, or one + /// that holds a value that is not a number, is the node's fault. + fn apply(&self, x: &[f32]) -> Result> { + ensure_node!( + x.len() == self.weight.len(), + "the output residual has {} values, the output norm {}", + x.len(), + self.weight.len() + ); + ensure_node!( + crate::error_bound::all_finite(x), + "the output residual holds a value that is not a number" + ); + let n = x.len() as f64; + let x: Vec = x.iter().map(|&v| f64::from(v)).collect(); + let mean = match self.kind { + NormKind::Rms => 0.0, + NormKind::Layer => x.iter().sum::() / n, + }; + let var = x.iter().map(|v| (v - mean) * (v - mean)).sum::() / n; + let scale = 1.0 / (var + self.eps).sqrt(); + Ok(x.iter() + .zip(&self.weight) + .enumerate() + .map(|(i, (v, w))| (v - mean) * scale * w + self.bias.as_ref().map_or(0.0, |b| b[i])) + .collect()) + } +} + +/// The claimed model's output head, read from its GGUF. +pub(crate) struct OutputHead { + /// The output matrix: `output.weight`, or the token embedding when the + /// model ties them. + weight: String, + bias: Option>, + norm: OutputNorm, +} + +/// Whether the logits a node opens are the output matrix's product up to a +/// uniform scale: no soft-capping comes after it. A check then compares +/// them with the matrix and judges the token on them. Otherwise it +/// computes the logits itself ([`check_computed_head`]). +pub fn logits_are_linear(weights: &WeightFile) -> bool { + !weights + .metadata + .keys() + .any(|k| k.ends_with(".final_logit_softcapping")) +} + +/// The output matrix of the claimed model: `output.weight`, or the token +/// embedding when the model ties them. +pub(crate) fn head_weight(weights: &WeightFile) -> &'static str { + if weights.tensors.contains_key("output.weight") { + "output.weight" + } else { + "token_embd.weight" + } +} + +impl OutputHead { + /// The bias of the logit of token `row`, 0 for a head without one. + pub(crate) fn bias_of(&self, row: usize) -> f64 { + self.bias.as_ref().map_or(0.0, |bias| bias[row]) + } + + pub(crate) fn from_weights(weights: &WeightFile) -> Result { + let arch = weights.metadata_str("general.architecture")?; + let float = |key: String| match weights.metadata.get(&key) { + Some(MetaValue::Float(value)) => Some(*value), + _ => None, + }; + let rms = float(format!("{arch}.attention.layer_norm_rms_epsilon")); + let layer = float(format!("{arch}.attention.layer_norm_epsilon")); + let (kind, eps) = match (rms, layer) { + (Some(eps), None) => (NormKind::Rms, eps), + (None, Some(eps)) => (NormKind::Layer, eps), + (Some(_), Some(_)) => { + bail!("the claimed GGUF names both an RMS and a layer norm epsilon") + } + (None, None) => bail!("the claimed GGUF names no norm epsilon"), + }; + let optional = |name: &str| { + weights + .tensors + .contains_key(name) + .then(|| weights.vector(name)) + .transpose() + }; + let weight = head_weight(weights); + let head = Self { + weight: weight.to_owned(), + bias: optional("output.bias")?, + norm: OutputNorm { + kind, + eps, + weight: weights.vector("output_norm.weight")?, + bias: optional("output_norm.bias")?, + }, + }; + let t = weights.tensor(&head.weight)?; + if t.row_len() as usize != head.norm.weight.len() { + bail!( + "{} rows have {} values, the output norm {}", + head.weight, + t.row_len(), + head.norm.weight.len() + ); + } + if let Some(bias) = &head.bias + && bias.len() as u64 != t.rows() + { + bail!("output.bias does not match {}", head.weight); + } + if let Some(bias) = &head.norm.bias + && bias.len() != head.norm.weight.len() + { + bail!( + "output_norm.bias has {} values, the output norm {}", + bias.len(), + head.norm.weight.len() + ); + } + Ok(head) + } + + /// The logits of every token at each residual. Reads the whole output + /// matrix once. + pub fn logits(&self, weights: &WeightFile, residuals: &[Vec]) -> Result>> { + let inputs = residuals + .iter() + .map(|x| self.norm.apply(x)) + .collect::>>()?; + let mut logits = self.products(weights, &inputs)?; + if self.bias.is_some() { + for values in &mut logits { + for (row, value) in values.iter_mut().enumerate() { + *value += self.bias_of(row); + } + } + } + Ok(logits) + } + + /// Fetches everything the head reads at once, and not row by row: the + /// norm, the bias and the whole output matrix. + pub(crate) fn prefetch(weights: &WeightFile) -> Result<()> { + let ranges = [ + "output.weight", + "output.bias", + "output_norm.weight", + "output_norm.bias", + ] + .into_iter() + .chain([head_weight(weights)]) + .filter(|name| weights.tensors.contains_key(*name)) + .map(|name| weights.tensor_range(name)) + .collect::>>()?; + weights.prefetch(&ranges) + } + + /// The product of the output matrix with each of `inputs`, one value + /// per row and without the bias. Reads the whole matrix once, split + /// over the machine's cores. + pub(crate) fn products( + &self, + weights: &WeightFile, + inputs: &[Vec], + ) -> Result>> { + let rows = weights.tensor(&self.weight)?.rows(); + let threads = std::thread::available_parallelism() + .map_or(1, std::num::NonZero::get) + .min(16) as u64; + let span = rows.div_ceil(threads).max(1); + let parts = std::thread::scope(|scope| { + let handles: Vec<_> = (0..rows) + .step_by(span as usize) + .map(|first| { + scope.spawn(move || -> Result>> { + let range = first..(first + span).min(rows); + let mut out = + vec![Vec::with_capacity((range.end - first) as usize); inputs.len()]; + weights.each_row(&self.weight, range, &mut |_, values| { + for (products, x) in out.iter_mut().zip(inputs) { + products.push(values.iter().zip(x).map(|(w, v)| w * v).sum()); + } + })?; + Ok(out) + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap_or_else(|_| bail!("a head thread panicked"))) + .collect::>>() + })?; + let mut logits = vec![Vec::with_capacity(rows as usize); inputs.len()]; + for part in parts { + for (all, slice) in logits.iter_mut().zip(part) { + all.extend(slice); + } + } + Ok(logits) + } +} + +/// One head position: the sampled token against the reference logits. +#[derive(Clone, Debug, PartialEq)] +pub struct PositionVerdict { + pub position: u32, + pub sampled: i32, + /// The token with the best reference logit. + pub best: i32, + /// The sampled token's logit less the best other token's. + pub margin: f64, + /// The tie band at this position, in logits. + pub band: f64, + /// Not the reference best, but within the band. + pub within_band: bool, + /// Whether the sampler let the check judge the token; when not, the + /// position passes on its logits alone. + pub judged: bool, + /// The check of the node's logits against the claimed output matrix, + /// when the check judged them instead of computing the head. + pub logits: Option, + /// The replay of the draw, for a sampled turn whose draw can be + /// replayed and whose token its filters keep. + pub draw: Option, + /// The token the turn's reasoning budget forced here, when it forced + /// one: the sampled token must be it, whatever the logits. + pub forced: Option, + /// Whether the token passed its judgement on the logits the node + /// opened, whatever the check of those logits found. The node signed + /// them, so a token they refuse is a defect anyone can see. + pub token_pass: bool, + pub pass: bool, +} + +/// The head check over every head position. +#[derive(Clone, Debug, PartialEq)] +pub struct HeadVerdict { + pub positions: Vec, + pub ties: usize, + /// Draws that pick the sampled token only with the band's help. A node + /// can steer those and no others. + pub band_draws: usize, + /// More ties, or more such draws, than [`allowed_ties`]: worth a second + /// look, not a failure. + pub flagged: bool, + pub pass: bool, +} + +/// Judges a greedy choice of `sampled` from `logits`. A sampled token the +/// vocabulary does not hold is the node's fault: the receipt names it. +pub fn judge(position: u32, logits: &[f64], sampled: i32) -> Result { + let Some(index) = usize::try_from(sampled).ok().filter(|&i| i < logits.len()) else { + node_fault!("position {position}: token {sampled} is outside the vocabulary"); + }; + // `f64::max` and `total_cmp` below would hide a logit that is not a + // number behind the others + if logits.iter().any(|l| !l.is_finite()) { + bail!("position {position}: a logit is not a number"); + } + let best = logits + .iter() + .enumerate() + .max_by(|a, b| a.1.total_cmp(b.1)) + .map(|(i, _)| i) + .context("the output head has no rows")?; + let other = logits + .iter() + .enumerate() + .filter(|&(i, _)| i != index) + .map(|(_, &v)| v) + .fold(f64::NEG_INFINITY, f64::max); + let band = TIE_BAND * root_mean_square(logits); + let margin = logits[index] - other; + let pass = margin >= -band; + Ok(PositionVerdict { + position, + sampled, + best: best as i32, + margin, + band, + within_band: pass && best != index, + judged: true, + logits: None, + draw: None, + forced: None, + token_pass: pass, + pass, + }) +} + +/// Judges the token `sampled` from `logits` at a position of a turn whose +/// reasoning budget `forcing` describes. A token the budget forced must be +/// the forced one: the sampler left it as the only candidate, so the +/// logits did not choose it. A budget the check could not replay leaves +/// the turn's tokens unjudged. Every other token is judged by `rule` +/// ([`judge_with`]). +pub(crate) fn judge_position( + rule: &TokenRule, + forcing: &Forcing, + position: u32, + logits: &[f64], + sampled: i32, +) -> Result { + let mut verdict = judge_forced(rule, forcing, position, logits, sampled)?; + verdict.token_pass = verdict.pass; + Ok(verdict) +} + +/// [`judge_position`] before it notes the token's own verdict. +fn judge_forced( + rule: &TokenRule, + forcing: &Forcing, + position: u32, + logits: &[f64], + sampled: i32, +) -> Result { + if matches!(rule, TokenRule::Unjudged(_)) { + return judge_with(rule, position, logits, sampled); + } + if let Some(reason) = forcing.unjudged() { + let unjudged = TokenRule::Unjudged(reason.to_owned()); + return judge_with(&unjudged, position, logits, sampled); + } + let Some(forced) = forcing.forced_at(position) else { + return judge_with(rule, position, logits, sampled); + }; + let mut verdict = judge(position, logits, sampled)?; + verdict.pass = sampled == forced; + verdict.within_band = false; + verdict.forced = Some(forced); + Ok(verdict) +} + +/// Judges the token `sampled` from `logits`, the logits the node opened, by +/// the turn's `rule`. A draw the rule replays is replayed on them: the node +/// sampled from those, so a draw that does not pick its token contradicts +/// the node's own opening, whoever checks it. +pub(crate) fn judge_with( + rule: &TokenRule, + position: u32, + logits: &[f64], + sampled: i32, +) -> Result { + let mut verdict = judge(position, logits, sampled)?; + match rule { + TokenRule::Greedy => {} + TokenRule::Filtered { + filters, biases, .. + } => { + verdict.pass = + TokenRule::keeps(filters, biases, logits, sampled as usize, verdict.band); + verdict.within_band = false; + } + TokenRule::Unjudged(_) => { + verdict.pass = true; + verdict.within_band = false; + verdict.judged = false; + } + } + if let Some(replayed) = rule.replayed_draw().filter(|_| verdict.pass) { + // the token sampled from a position takes the next one + let replay = draw::judge( + replayed.draw, + replayed.filters, + &sampling::biased(logits, replayed.biases), + sampled as usize, + u64::from(position) + 1, + DRAW_BAND * root_mean_square(logits), + ); + verdict.pass = replay.pass; + verdict.draw = Some(replay); + } + Ok(verdict) +} + +/// The token rule of `receipt`'s sampler. An unbound receipt states none, +/// and is judged as greedy, as an audit asks for. +pub fn token_rule(receipt: &Receipt) -> TokenRule { + receipt + .binding + .as_ref() + .map_or(TokenRule::Greedy, |b| TokenRule::from_sampler(&b.sampler)) +} + +/// The token rule of `receipt`'s sampler for the claimed model. +/// +/// The runtime takes the model's suppressed tokens out of every candidate +/// list, and for a turn that ignores its end the end-of-generation tokens +/// too ([`TokenRule::without`]). `is_end` says whether a token is one of +/// the second, as the claimed model's vocabulary does (`llama_vocab_is_eog`); +/// it is asked only for a turn that ignores its end, of every token of +/// the output head. +/// +/// A model whose logits are not the matrix's product gets no token +/// judgement: see [`TIE_BAND`]. +pub fn token_rule_for( + weights: &WeightFile, + receipt: &Receipt, + is_end: &dyn Fn(i32) -> Result, +) -> TokenRule { + if !logits_are_linear(weights) { + return TokenRule::Unjudged( + "the model soft-caps its logits, so the check cannot judge tokens on the logits \ + the node sampled from" + .into(), + ); + } + let rule = token_rule(receipt); + let mut excluded = weights.suppressed_tokens().to_vec(); + let ignores_end = receipt + .binding + .as_ref() + .is_some_and(|b| sampling::ignores_end_tokens(&b.sampler)); + if ignores_end { + match end_tokens(weights, is_end) { + Ok(tokens) => excluded.extend(tokens), + Err(error) => { + let reason = format!( + "the claimed model's vocabulary does not name its end-of-generation \ + tokens: {error:#}" + ); + return rule.without(Err(&reason)); + } + } + } + rule.without(Ok(&excluded)) +} + +/// The end-of-generation tokens among the rows of the claimed output head. +fn end_tokens(weights: &WeightFile, is_end: &dyn Fn(i32) -> Result) -> Result> { + let rows = weights.tensor(head_weight(weights))?.rows(); + let rows = i32::try_from(rows).context("the output head has more rows than tokens")?; + let mut tokens = Vec::new(); + for token in 0..rows { + if is_end(token)? { + tokens.push(token); + } + } + Ok(tokens) +} + +/// Checks the token sampled from each opened head position without a head +/// key, as a recheck of evidence does, by `rule` ([`token_rule_for`]). It +/// reads the whole output matrix. +/// +/// It checks the logits the stage on `backend` opened against every row +/// of the matrix and judges the token on them +/// ([`every_row::check_head_on_every_row`]), which is what an audit does +/// with its key ([`key::check_head_with_key`]). For a model whose logits +/// are not the matrix's product it checks the final residuals alone +/// ([`check_computed_head`]). +/// +/// `forcing` says which tokens the turn's reasoning budget forced +/// ([`reasoning_budget::replay`]). +/// +/// An error that blames the node ([`crate::node_fault::NodeFault`]) is a +/// defect of the opening. Any other error is the auditor's. +pub fn check_head( + weights: &WeightFile, + receipt: &Receipt, + openings: &[HeadOpening], + backend: &str, + rows_seed: &[u8], + checked: (&TokenRule, &Forcing), +) -> Result { + if logits_are_linear(weights) { + every_row::check_head_on_every_row(weights, receipt, openings, backend, rows_seed, checked) + } else { + check_computed_head(weights, receipt, openings, checked) + } +} + +/// For a model that soft-caps its logits: checks that each opened final +/// residual fits the claimed output head, and passes each token to `rule`, +/// which for such a model judges none ([`token_rule_for`]). +pub fn check_computed_head( + weights: &WeightFile, + receipt: &Receipt, + openings: &[HeadOpening], + (rule, forcing): (&TokenRule, &Forcing), +) -> Result { + OutputHead::prefetch(weights)?; + let head = OutputHead::from_weights(weights)?; + let residuals = openings + .iter() + .map(|opening| opening.residual_values().or_node_fault()) + .collect::>>()?; + let logits = head.logits(weights, &residuals)?; + let positions = openings + .iter() + .zip(&logits) + .map(|(opening, logits)| { + let sampled = receipt.sampled_after(opening.position).with_context(|| { + format!("no token was sampled at position {}", opening.position) + })?; + judge_position(rule, forcing, opening.position, logits, sampled) + }) + .collect::>>()?; + Ok(verdict(positions)) +} + +fn verdict(positions: Vec) -> HeadVerdict { + let ties = positions.iter().filter(|p| p.within_band).count(); + let band_draws = positions + .iter() + .filter(|p| p.draw.is_some_and(|draw| draw.pass && !draw.exact)) + .count(); + let allowed = allowed_ties(positions.len()); + HeadVerdict { + ties, + band_draws, + flagged: ties > allowed || band_draws > allowed, + pass: !positions.is_empty() && positions.iter().all(|p| p.pass), + positions, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::weights::test_gguf; + + #[test] + fn the_best_token_passes_and_a_near_tie_is_counted() { + let logits = [1.0, 5.0, 4.999, -3.0]; + let best = judge(7, &logits, 1).unwrap(); + assert!(best.pass && !best.within_band); + assert!((best.margin - 0.001).abs() < 1e-9); + let tie = judge(7, &logits, 2).unwrap(); + assert!(tie.pass && tie.within_band); + assert_eq!(tie.best, 1); + let wrong = judge(7, &logits, 0).unwrap(); + assert!(!wrong.pass); + assert!(judge(7, &logits, 4).is_err()); + assert!(judge(7, &logits, -1).is_err()); + } + + #[test] + fn a_residual_or_token_that_does_not_fit_the_head_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + let weights = model(true, false); + let head = OutputHead::from_weights(&weights).unwrap(); + for residual in [ + vec![1.0, 2.0], + vec![1.0, f32::NAN, 2.0], + vec![f32::INFINITY, 0.0, 2.0], + ] { + let error = head.logits(&weights, &[residual]).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + } + let error = judge(7, &[1.0, 5.0], 2).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + // a logit that is not a number cannot be judged: `f64::max` would + // skip it and pass the token + assert!(judge(7, &[1.0, f64::NAN, 0.5], 0).is_err()); + } + + #[test] + fn many_ties_are_flagged_and_no_position_fails() { + let tie = |position| judge(position, &[5.0, 4.999], 1).unwrap(); + let v = verdict(vec![tie(1), judge(2, &[5.0, 1.0], 0).unwrap()]); + assert!(v.pass && !v.flagged); + let v = verdict(vec![tie(1), tie(2), tie(3)]); + assert!(v.pass && v.flagged); + assert!(!verdict(Vec::new()).pass); + } + + /// A rule that replays the draw of `seed` over every token. + fn drawn(seed: u32) -> TokenRule { + TokenRule::Filtered { + filters: Vec::new(), + biases: Vec::new(), + draw: sampling::DrawRule::Indexed(draw::IndexedDraw { + seed, + temperature: 1.0, + }), + } + } + + #[test] + fn a_sampled_token_is_the_one_its_draw_picks() { + // weights 1 and 3: the draw picks token 0 below 0.25, else token 1 + let logits = [0.0, 3f64.ln()]; + let rule = drawn(42); + for position in 0..40u32 { + let u = draw::uniform(42, u64::from(position) + 1); + // away from the boundary, where the tie band could admit both + if (u - 0.25).abs() < 0.05 { + continue; + } + let picked = i32::from(u >= 0.25); + let right = judge_with(&rule, position, &logits, picked).unwrap(); + assert!( + right.pass && right.draw.is_some_and(|d| d.exact), + "{right:?}" + ); + let wrong = judge_with(&rule, position, &logits, 1 - picked).unwrap(); + assert!( + !wrong.pass && wrong.draw.is_some_and(|d| !d.pass), + "{wrong:?}" + ); + } + let position = (0..40u32) + .find(|&p| draw::uniform(42, u64::from(p) + 1) > 0.6) + .unwrap(); + // a rule without a draw judges the kept token alone + let unreplayed = TokenRule::Filtered { + filters: Vec::new(), + biases: Vec::new(), + draw: sampling::DrawRule::Unjudged("no draw".into()), + }; + let verdict = judge_with(&unreplayed, position, &logits, 0).unwrap(); + assert!(verdict.pass && verdict.draw.is_none()); + } + + #[test] + fn a_token_the_reasoning_budget_forced_must_be_the_forced_one() { + // the draw picks token 0 below 0.25, else token 1 + let logits = [0.0, 3f64.ln()]; + let rule = drawn(42); + let position = (0..40u32) + .find(|&p| draw::uniform(42, u64::from(p) + 1) > 0.6) + .unwrap(); + // the budget forced token 0 here: the draw's token 1 is not it + let forcing = Forcing::forced(&[(position, 0)]); + let forced = judge_position(&rule, &forcing, position, &logits, 0).unwrap(); + assert!(forced.pass && forced.judged, "{forced:?}"); + assert_eq!((forced.forced, forced.draw), (Some(0), None)); + let drawn_token = judge_position(&rule, &forcing, position, &logits, 1).unwrap(); + assert!(!drawn_token.pass && drawn_token.forced == Some(0)); + // every other position of the turn is judged by the draw + let free = Forcing::forced(&[(position + 1, 0)]); + for forcing in [&free, &Forcing::Free] { + let right = judge_position(&rule, forcing, position, &logits, 1).unwrap(); + assert!(right.pass && right.draw.is_some_and(|d| d.exact)); + assert_eq!(right.forced, None); + let wrong = judge_position(&rule, forcing, position, &logits, 0).unwrap(); + assert!(!wrong.pass, "{wrong:?}"); + } + // a greedy-like rule too: the forced token need not be the best + let greedy = TokenRule::Filtered { + filters: vec![sampling::Filter::TopK(1)], + biases: Vec::new(), + draw: sampling::DrawRule::Single, + }; + assert!( + judge_position(&greedy, &forcing, position, &logits, 0) + .unwrap() + .pass + ); + assert!( + !judge_position(&greedy, &Forcing::Free, position, &logits, 0) + .unwrap() + .pass + ); + // a budget the check could not replay leaves the token unjudged + let unjudged = Forcing::Unjudged("no tokenizer".into()); + let verdict = judge_position(&rule, &unjudged, position, &logits, 0).unwrap(); + assert!(verdict.pass && !verdict.judged && verdict.draw.is_none()); + // and a sampler that is beyond the check stays so, forced or not + let beyond = TokenRule::Unjudged("a grammar".into()); + let verdict = judge_position(&beyond, &forcing, position, &logits, 1).unwrap(); + assert!(verdict.pass && !verdict.judged && verdict.forced.is_none()); + } + + #[test] + fn a_draw_near_a_boundary_has_a_narrow_band() { + // weights 1 and 3: the boundary between the tokens is at 0.25 + let logits = [0.0, 3f64.ln()]; + let rule = drawn(42); + // a draw within 2e-3 of the boundary, on its upper side: token 1 + let position = (0..200_000u32) + .find(|&p| { + let u = draw::uniform(42, u64::from(p) + 1); + u > 0.2501 && u < 0.252 + }) + .expect("a draw near the boundary"); + let judged = |token: i32| judge_with(&rule, position, &logits, token).unwrap(); + // on the node's own logits the draw picks token 1, and the narrow + // band admits no other + assert!(judged(1).pass); + let steered = judged(0); + assert!(!steered.pass, "{steered:?}"); + const { assert!(DRAW_BAND < TIE_BAND / 10.0) }; + } + + #[test] + fn draws_that_pass_only_within_the_band_are_counted_and_flagged() { + let position = |exact: bool| { + let mut p = judge(1, &[5.0, 1.0], 0).unwrap(); + p.draw = Some(draw::DrawVerdict { + uniform: 0.5, + lower: 0.0, + upper: 1.0, + exact, + pass: true, + }); + p + }; + let v = verdict(vec![position(true), position(false), position(true)]); + assert_eq!((v.band_draws, v.flagged, v.pass), (1, false, true)); + let v = verdict(vec![position(false), position(false), position(true)]); + assert_eq!((v.band_draws, v.flagged, v.pass), (2, true, true)); + } + + fn model(tied: bool, layer_norm: bool) -> WeightFile { + let embd = vec![ + 1.0, 0.0, 0.0, // + 0.0, 1.0, 0.0, // + 0.0, 0.0, 1.0, // + 1.0, 1.0, -1.0, + ]; + let mut tensors = vec![ + ("output_norm.weight", vec![3], vec![1.0, 2.0, 0.5]), + ("token_embd.weight", vec![3, 4], embd.clone()), + ]; + if !tied { + let reversed: Vec = embd.iter().map(|v| -v).collect(); + tensors.push(("output.weight", vec![3, 4], reversed)); + } + let eps_key = if layer_norm { + "toy.attention.layer_norm_epsilon" + } else { + "toy.attention.layer_norm_rms_epsilon" + }; + test_gguf::open( + &[ + ("general.architecture", MetaValue::Str("toy".into())), + (eps_key, MetaValue::Float(1e-6)), + ], + &tensors, + ) + } + + #[test] + fn the_head_is_the_output_norm_and_matrix() { + let weights = model(true, false); + let head = OutputHead::from_weights(&weights).unwrap(); + let x = vec![3.0f32, 0.0, 4.0]; + let logits = head.logits(&weights, &[x]).unwrap(); + // rms of (3, 0, 4) is sqrt(25 / 3); scaled by the norm weight + let s = 1.0 / (25.0f64 / 3.0 + 1e-6).sqrt(); + let normed = [3.0 * s, 0.0, 4.0 * 0.5 * s]; + let expected = [ + normed[0], + normed[1], + normed[2], + normed[0] + normed[1] - normed[2], + ]; + for (got, want) in logits[0].iter().zip(expected) { + assert!((got - want).abs() < 1e-12, "{got} {want}"); + } + // an untied model uses its own output matrix + let untied = model(false, false); + let logits = OutputHead::from_weights(&untied) + .unwrap() + .logits(&untied, &[vec![3.0, 0.0, 4.0]]) + .unwrap(); + assert!((logits[0][0] + normed[0]).abs() < 1e-12); + } + + #[test] + fn a_norm_bias_shorter_than_the_norm_is_refused_not_a_panic() { + let embd = vec![1.0; 12]; + let weights = test_gguf::open( + &[ + ("general.architecture", MetaValue::Str("toy".into())), + ("toy.attention.layer_norm_epsilon", MetaValue::Float(1e-6)), + ], + &[ + ("output_norm.weight", vec![3], vec![1.0, 2.0, 0.5]), + ("output_norm.bias", vec![2], vec![0.0, 0.0]), + ("token_embd.weight", vec![3, 4], embd), + ], + ); + let error = OutputHead::from_weights(&weights).err().expect("refused"); + assert!(error.to_string().contains("output_norm.bias"), "{error}"); + } + + #[test] + fn a_layer_norm_subtracts_the_mean() { + let weights = model(true, true); + let head = OutputHead::from_weights(&weights).unwrap(); + // a constant residual normalizes to zero + let logits = head.logits(&weights, &[vec![2.0, 2.0, 2.0]]).unwrap(); + assert!(logits[0].iter().all(|v| v.abs() < 1e-9)); + } + + #[test] + fn many_threads_give_every_row_in_order() { + let rows = 1000u64; + let embd: Vec = (0..rows).flat_map(|r| [r as f32, 0.0]).collect(); + let weights = test_gguf::open( + &[ + ("general.architecture", MetaValue::Str("toy".into())), + ( + "toy.attention.layer_norm_rms_epsilon", + MetaValue::Float(0.0), + ), + ], + &[ + ("output_norm.weight", vec![2], vec![1.0, 1.0]), + ("token_embd.weight", vec![2, rows], embd), + ], + ); + let head = OutputHead::from_weights(&weights).unwrap(); + let logits = head.logits(&weights, &[vec![1.0, 1.0]]).unwrap(); + assert_eq!(logits[0].len(), rows as usize); + assert!(logits[0].windows(2).all(|w| w[0] < w[1])); + } +} diff --git a/crates/skippy-receipts/src/head/draw.rs b/crates/skippy-receipts/src/head/draw.rs new file mode 100644 index 00000000..25bfa16e --- /dev/null +++ b/crates/skippy-receipts/src/head/draw.rs @@ -0,0 +1,299 @@ +//! Replays the draw of a sampled turn. +//! +//! A turn whose statement names the [`crate::turn::INDEXED_DRAW`] rule drew +//! the token at position `i` of its sequence with [`uniform`]`(seed, i)`: +//! over the candidates its filters kept, in token id order, it took the +//! first whose running softmax weight passed the uniform times the total. +//! The seed, the position and the logits fix the token, so a client that +//! checked the logits finds the token the node had to take. +//! +//! The logits the draw is replayed on may differ from the ones the node +//! drew from, each within a band. The band can move a boundary between two +//! tokens, and it can move a token into or out of the kept candidates. So a +//! token passes when the uniform lies in the widest interval the band +//! allows for it ([`judge`]): the interval's lower end takes every weight +//! below the token at its least and every other weight at its most, and +//! the upper end the reverse. A draw that passes only with the band is +//! counted, since a node can steer the draws that land that close to a +//! boundary and no others. +//! +//! The band is narrow ([`super::DRAW_BAND`]): the draw is replayed on the +//! logits the node opened, which it drew from, so only the last bits of +//! `exp` can differ. +//! +//! The draw without the band is the runtime's own arithmetic +//! ([`runtime_chain`]): its filters work in f32, and an f32 top-p can cut +//! the candidates before an f64 one would. The token that arithmetic picks +//! passes, and the candidates it keeps widen the sets the band allows. + +use super::sampling::Filter; + +mod runtime_chain; + +/// The uniform in `[0, 1)` that picks the token at position `index` of a +/// sequence drawn with `seed`: the 53 high bits of SplitMix64 over the seed +/// and the low 32 bits of the index. The node computes the same value +/// (`skippy_receipt_draw_uniform`). +pub fn uniform(seed: u32, index: u64) -> f64 { + let mut x = (u64::from(seed) << 32) | (index & 0xFFFF_FFFF); + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^= x >> 31; + (x >> 11) as f64 / (1u64 << 53) as f64 +} + +/// The draw a statement names: its seed, and the temperature the logits +/// were divided by before the draw. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IndexedDraw { + pub seed: u32, + pub temperature: f64, +} + +/// One replayed draw. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DrawVerdict { + /// The uniform of the draw. + pub uniform: f64, + /// The uniforms that pick the sampled token, at the widest the band + /// allows: from `lower` up to `upper`, which is not included. + pub lower: f64, + pub upper: f64, + /// The uniform picks the sampled token on the checked logits as they + /// are, with no help from the band. + pub exact: bool, + pub pass: bool, +} + +/// The candidates in order of their logits, best first. +struct Ranked { + /// Logits, best first. + logits: Vec, + /// By token, its place in `logits`. + rank: Vec, +} + +impl Ranked { + fn new(logits: &[f64]) -> Self { + let mut order: Vec = (0..logits.len() as u32).collect(); + order.sort_unstable_by(|&a, &b| { + logits[b as usize] + .total_cmp(&logits[a as usize]) + .then(a.cmp(&b)) + }); + let mut rank = vec![0u32; logits.len()]; + for (place, &token) in order.iter().enumerate() { + rank[token as usize] = place as u32; + } + Self { + logits: order.iter().map(|&t| logits[t as usize]).collect(), + rank, + } + } +} + +/// How many of the best `sorted` logits the filters keep, applied in order +/// as the runtime's sampler chain applies them. +fn kept(sorted: &[f64], filters: &[Filter]) -> usize { + let Some(&best) = sorted.first() else { + return 0; + }; + let mut n = sorted.len(); + // what the logits are multiplied by, after the temperatures so far + let mut scale = 1.0; + for filter in filters { + match *filter { + Filter::TopK(0) => {} + Filter::TopK(k) => n = n.min(k as usize), + Filter::TopP(p) if p >= 1.0 => {} + Filter::TopP(p) => { + let weight = |l: f64| ((l - best) * scale).exp(); + let total: f64 = sorted[..n].iter().map(|&l| weight(l)).sum(); + let mut running = 0.0; + for (i, &l) in sorted[..n].iter().enumerate() { + running += weight(l); + if running >= p * total { + n = i + 1; + break; + } + } + } + Filter::MinP(p) if p <= 0.0 => {} + Filter::MinP(p) => { + let least = best * scale + p.ln(); + n = sorted[..n].partition_point(|&l| l * scale >= least).max(1); + } + Filter::Temperature(t) => scale /= t, + } + } + n +} + +/// Whether the token at `place` can be kept when every logit moves by up to +/// `band`: the logits above it at their least, itself and the rest at +/// their most. Only differences matter, so the logits above move down by +/// twice the band. +fn possibly_kept(ranked: &Ranked, filters: &[Filter], place: usize, band: f64) -> bool { + let (above, rest) = ranked.logits.split_at(place); + let token = rest[0]; + let lowered: Vec = above.iter().map(|l| l - 2.0 * band).collect(); + // the lowered logits that still beat the token stay above it + let still_above = lowered.partition_point(|&l| l > token); + let mut moved = Vec::with_capacity(ranked.logits.len()); + moved.extend_from_slice(&lowered[..still_above]); + merge_descending(&mut moved, &lowered[still_above..], rest); + // the token comes first among its equals + let at = moved.partition_point(|&l| l > token); + at < kept(&moved, filters) +} + +/// Whether the token at `place` is kept however the logits move by up to +/// `band`: itself at its least and every other at its most, so it moves +/// down by twice the band. +fn surely_kept(ranked: &Ranked, filters: &[Filter], place: usize, band: f64) -> bool { + let token = ranked.logits[place] - 2.0 * band; + let mut moved = Vec::with_capacity(ranked.logits.len()); + moved.extend_from_slice(&ranked.logits[..place]); + moved.extend_from_slice(&ranked.logits[place + 1..]); + // the token comes last among its equals + let at = moved.partition_point(|&l| l >= token); + moved.insert(at, token); + at < kept(&moved, filters) +} + +/// The first of `places` places where `stops` holds, or `places` when it +/// holds at none. `stops` holds from one place on. +fn first_place(places: usize, stops: impl Fn(usize) -> bool) -> usize { + let (mut low, mut high) = (0, places); + while low < high { + let middle = low + (high - low) / 2; + if stops(middle) { + high = middle; + } else { + low = middle + 1; + } + } + low +} + +/// Appends `a` and `b`, both best first, to `out` in that order. +fn merge_descending(out: &mut Vec, a: &[f64], b: &[f64]) { + let (mut i, mut j) = (0, 0); + while i < a.len() && j < b.len() { + if a[i] > b[j] { + out.push(a[i]); + i += 1; + } else { + out.push(b[j]); + j += 1; + } + } + out.extend_from_slice(&a[i..]); + out.extend_from_slice(&b[j..]); +} + +/// The weights of a draw, by token, with each token's place by logit. +struct Bound<'a> { + weights: &'a [f64], + rank: &'a [u32], + sampled: usize, +} + +impl Bound<'_> { + /// The share of the weight before `end`, a token id, among all of it: + /// tokens before `end` count when their place is under `before`, at + /// `before_factor` of their weight, and the others under `after`, at + /// `after_factor`. + fn share(&self, end: usize, before: (usize, f64), after: (usize, f64)) -> f64 { + let mut head = 0.0; + let mut tail = 0.0; + for (token, (&w, &place)) in self.weights.iter().zip(self.rank).enumerate() { + let place = place as usize; + if token < end { + if place < before.0 { + head += w * before.1; + } + } else if place < after.0 { + tail += w * after.1; + } + } + if head + tail > 0.0 { + head / (head + tail) + } else { + 0.0 + } + } + + /// The uniforms that pick the sampled token, at the widest: from the + /// lower end up to the upper, which is not included. The lower end + /// counts the `sure` best candidates before the token at their weight + /// divided by `factor`, and the `possible` best from the token on at + /// their weight times `factor`. The upper end counts the `possible` + /// best up to the token at their most and the `sure` best after it at + /// their least. + fn interval(&self, sure: usize, possible: usize, factor: f64) -> (f64, f64) { + let lower = self.share(self.sampled, (sure, 1.0 / factor), (possible, factor)); + let upper = self.share(self.sampled + 1, (possible, factor), (sure, 1.0 / factor)); + (lower, upper) + } +} + +/// Replays the draw of token `sampled` at position `index` from `logits`, +/// which already hold the turn's logit biases. `filters` are the turn's +/// candidate filters in order, and `band` the slack of each logit for the +/// node's rounding. +pub(crate) fn judge( + draw: IndexedDraw, + filters: &[Filter], + logits: &[f64], + sampled: usize, + index: u64, + band: f64, +) -> DrawVerdict { + let uniform = uniform(draw.seed, index); + let ranked = Ranked::new(logits); + let n = ranked.logits.len(); + // the temperatures between filters divide in the chain, the rest after + let within: f64 = filters + .iter() + .map(|f| match f { + Filter::Temperature(t) => *t, + _ => 1.0, + }) + .product(); + let runtime = runtime_chain::pick(logits, filters, draw.temperature / within, uniform); + let kept_here = kept(&ranked.logits, filters); + // a better logit is kept whenever a worse one is, so each set is the + // best logits up to one place + let possible = first_place(n, |place| !possibly_kept(&ranked, filters, place, band)) + .max(kept_here) + .max(runtime.kept); + let sure = first_place(n, |place| !surely_kept(&ranked, filters, place, band)) + .min(kept_here) + .min(runtime.kept); + let best = ranked.logits.first().copied().unwrap_or(0.0); + let weights: Vec = logits + .iter() + .map(|l| ((l - best) / draw.temperature).exp()) + .map(|w| if w.is_finite() { w } else { 0.0 }) + .collect(); + let bound = Bound { + weights: &weights, + rank: &ranked.rank, + sampled, + }; + let place = ranked.rank[sampled] as usize; + let exact = runtime.token as usize == sampled; + let (lower, upper) = bound.interval(sure, possible, (band / draw.temperature).exp()); + DrawVerdict { + uniform, + lower, + upper, + exact, + pass: exact || (place < possible && (lower..upper).contains(&uniform)), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/head/draw/runtime_chain.rs b/crates/skippy-receipts/src/head/draw/runtime_chain.rs new file mode 100644 index 00000000..7c3432a1 --- /dev/null +++ b/crates/skippy-receipts/src/head/draw/runtime_chain.rs @@ -0,0 +1,214 @@ +//! The node's sampler chain and indexed draw as the runtime computes them, +//! for the draw's exact replay. +//! +//! llama.cpp filters the candidates in f32, in the order it holds them: +//! token id order until a filter sorts them. Top-p normalizes the softmax +//! over the candidates with an f32 sum, which drops the weights of a long +//! tail that fall under half an ulp of the running sum, so its cut can come +//! before the cut of the same mass in f64. This port follows that +//! arithmetic: `llama_sampler_top_k_impl`, `llama_sampler_top_p_apply`, +//! `llama_sampler_min_p_apply` and `llama_sampler_temp_impl` of +//! `src/llama-sampler.cpp` with `min_keep` 0, as `src/skippy/sampling_config.cpp` +//! builds them, then `skippy_receipt_draw_pick` of +//! `src/skippy/receipts_draw.cpp`. A change of those needs the same change +//! here. +//! +//! Where llama.cpp orders equal logits, it does so in no fixed order; this +//! port puts the lower token id first. The replay's band covers the rest +//! ([`super::judge`]). + +use super::super::sampling::Filter; + +/// The candidates of the chain, as the runtime holds them. +struct Candidates { + ids: Vec, + logits: Vec, + /// A filter sorted them, best first. + sorted: bool, +} + +impl Candidates { + fn new(logits: &[f64]) -> Self { + Self { + ids: (0..logits.len() as u32).collect(), + // the logits already hold the biases, added in f32 + logits: logits.iter().map(|&l| l as f32).collect(), + sorted: false, + } + } + + fn len(&self) -> usize { + self.ids.len() + } + + fn truncate(&mut self, n: usize) { + self.ids.truncate(n); + self.logits.truncate(n); + } + + fn sort(&mut self) { + if self.sorted { + return; + } + let mut order: Vec = (0..self.len()).collect(); + order.sort_by(|&a, &b| { + self.logits[b] + .total_cmp(&self.logits[a]) + .then(self.ids[a].cmp(&self.ids[b])) + }); + self.ids = order.iter().map(|&i| self.ids[i]).collect(); + self.logits = order.iter().map(|&i| self.logits[i]).collect(); + self.sorted = true; + } + + fn top_k(&mut self, k: u32) { + if k == 0 { + return; + } + let k = (k as usize).min(self.len()); + self.sort(); + self.truncate(k); + } + + /// The softmax of the candidates in their order, in f32 + /// (`llama_sampler_softmax_impl` without a sort). + fn softmax(&self) -> Vec { + let max = if self.sorted { + self.logits[0] + } else { + self.logits.iter().copied().fold(self.logits[0], f32::max) + }; + let mut probabilities: Vec = self.logits.iter().map(|&l| (l - max).exp()).collect(); + let mut total = 0.0f32; + for &p in &probabilities { + total += p; + } + for p in &mut probabilities { + *p /= total; + } + probabilities + } + + fn top_p(&mut self, p: f32) { + if p >= 1.0 || self.len() == 0 { + return; + } + let probabilities = self.softmax(); + // the cumulative sum runs best first; the probabilities follow the + // candidates through the sort + let mut order: Vec = (0..self.len()).collect(); + if !self.sorted { + order.sort_by(|&a, &b| { + self.logits[b] + .total_cmp(&self.logits[a]) + .then(self.ids[a].cmp(&self.ids[b])) + }); + } + let mut cumulative = 0.0f32; + let mut last = order.len(); + for (i, &at) in order.iter().enumerate() { + cumulative += probabilities[at]; + if cumulative >= p { + last = i + 1; + break; + } + } + self.ids = order[..last].iter().map(|&i| self.ids[i]).collect(); + self.logits = order[..last].iter().map(|&i| self.logits[i]).collect(); + self.sorted = true; + } + + fn min_p(&mut self, p: f32) { + if p <= 0.0 || self.len() == 0 { + return; + } + if !self.sorted { + let max = self.logits.iter().copied().fold(-f32::MAX, f32::max); + let least = max + p.ln(); + let kept: Vec = (0..self.len()) + .filter(|&i| self.logits[i] >= least) + .collect(); + if !kept.is_empty() { + self.ids = kept.iter().map(|&i| self.ids[i]).collect(); + self.logits = kept.iter().map(|&i| self.logits[i]).collect(); + return; + } + } + self.sort(); + let least = self.logits[0] + p.ln(); + let kept = 1 + self.logits[1..].iter().take_while(|&&l| l >= least).count(); + self.truncate(kept); + } + + fn divide(&mut self, temperature: f32) { + for l in &mut self.logits { + *l /= temperature; + } + } +} + +/// What the runtime's chain and draw make of one position. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct RuntimePick { + /// The token the draw picks. + pub(super) token: u32, + /// How many candidates the filters keep. + pub(super) kept: usize, +} + +/// The token the runtime picks at the uniform `u` from `logits`, the +/// node's logits with the turn's biases, by token. `filters` are the +/// chain's filters in order, and `temperature` what the logits are divided +/// by after the last of them. +pub(super) fn pick(logits: &[f64], filters: &[Filter], temperature: f64, u: f64) -> RuntimePick { + let mut candidates = Candidates::new(logits); + for filter in filters { + match *filter { + Filter::TopK(k) => candidates.top_k(k), + Filter::TopP(p) => candidates.top_p(p as f32), + Filter::MinP(p) => candidates.min_p(p as f32), + Filter::Temperature(t) => candidates.divide(t as f32), + } + } + let kept = candidates.len(); + // each temperature after the last filter divides in turn; their + // product rounds the same up to the last bit, which the band covers + if temperature != 1.0 { + for l in &mut candidates.logits { + *l = (f64::from(*l) / temperature) as f32; + } + } + RuntimePick { + token: draw(&candidates, u), + kept, + } +} + +/// `skippy_receipt_draw_pick`: weights against the best logit in f64, a +/// weight that is not a number counting as 0, and the first candidate in +/// token id order whose running weight passes the uniform times the total. +/// When every weight is 0, the last candidate in token id order. +fn draw(candidates: &Candidates, u: f64) -> u32 { + let Some(&first) = candidates.logits.first() else { + return 0; + }; + let best = candidates.logits.iter().copied().fold(first, f32::max); + let weights: Vec = candidates + .logits + .iter() + .map(|&l| (f64::from(l) - f64::from(best)).exp()) + .map(|w| if w.is_finite() { w } else { 0.0 }) + .collect(); + let total: f64 = weights.iter().sum(); + let mut order: Vec = (0..candidates.len()).collect(); + order.sort_by_key(|&i| candidates.ids[i]); + let target = u * total; + let mut running = 0.0; + for &i in &order { + running += weights[i]; + if running > target { + return candidates.ids[i]; + } + } + order.last().map_or(0, |&i| candidates.ids[i]) +} diff --git a/crates/skippy-receipts/src/head/draw/tests.rs b/crates/skippy-receipts/src/head/draw/tests.rs new file mode 100644 index 00000000..2930995f --- /dev/null +++ b/crates/skippy-receipts/src/head/draw/tests.rs @@ -0,0 +1,232 @@ +use super::*; + +/// Shared with the node's test (`tests/test-skippy-receipt-draw.cpp` in the +/// llama.cpp patch): the seed, the index, and the uniform times 2^53. +const VECTORS: [(u32, u64, u64); 9] = [ + (0, 0, 0x1c_4415_072f_63b9), + (0, 1, 0x12_2145_bd91_204b), + (0, 4096, 0x1a_e753_47b2_83cf), + (1, 0, 0x18_858b_4354_7040), + (1, 7, 0x04_f9e2_e0f8_dc3a), + (42, 1, 0x0d_32e6_600c_0afe), + (42, 4_294_967_295, 0x1f_14ea_3899_a69f), + (4_294_967_295, 4096, 0x00_ca3f_ff38_9d1d), + (123_456_789, 7, 0x1f_6601_39cb_7f55), +]; + +#[test] +fn the_uniform_is_the_one_the_node_computes() { + for (seed, index, bits) in VECTORS { + let u = uniform(seed, index); + assert_eq!(u, bits as f64 / (1u64 << 53) as f64, "{seed} {index}"); + assert!((0.0..1.0).contains(&u)); + } + // only the low 32 bits of the index enter + assert_eq!(uniform(7, 5), uniform(7, (1 << 32) + 5)); +} + +/// A seed and index whose uniform lies in `range`. +fn index_with_uniform(seed: u32, range: std::ops::Range) -> u64 { + (0..10_000) + .find(|&index| range.contains(&uniform(seed, index))) + .expect("an index in the range") +} + +const DRAW: IndexedDraw = IndexedDraw { + seed: 42, + temperature: 1.0, +}; + +/// Weights 1, 2, 1 for tokens 0, 1, 2: boundaries at 0.25 and 0.75. +fn three() -> Vec { + vec![0.0, 2f64.ln(), 0.0] +} + +#[test] +fn a_draw_picks_the_token_whose_interval_holds_the_uniform() { + let logits = three(); + for (token, range) in [(0, 0.0..0.25), (1, 0.25..0.75), (2, 0.75..1.0)] { + let inner = (range.start + 0.05)..(range.end - 0.05); + let index = index_with_uniform(DRAW.seed, inner); + let verdict = judge(DRAW, &[], &logits, token, index, 0.0); + assert!(verdict.pass && verdict.exact, "{token}: {verdict:?}"); + assert!((verdict.lower - range.start).abs() < 1e-12); + assert!((verdict.upper - range.end).abs() < 1e-12); + // every other token fails at that uniform + for other in (0..3).filter(|&other| other != token) { + let verdict = judge(DRAW, &[], &logits, other, index, 0.0); + assert!(!verdict.pass && !verdict.exact, "{other}: {verdict:?}"); + } + } +} + +#[test] +fn the_band_admits_only_a_draw_near_a_boundary() { + let logits = three(); + // just above the boundary at 0.25: token 1 on these logits + let index = index_with_uniform(DRAW.seed, 0.2501..0.2520); + let exact = judge(DRAW, &[], &logits, 1, index, 0.0); + assert!(exact.pass && exact.exact); + // token 0 passes only with a band that can move the boundary that far + assert!(!judge(DRAW, &[], &logits, 0, index, 0.0).pass); + let banded = judge(DRAW, &[], &logits, 0, index, 0.01); + assert!(banded.pass && !banded.exact, "{banded:?}"); + assert!(banded.upper > 0.252 && banded.upper < 0.27); + // token 2's interval starts near 0.75, band or not + assert!(!judge(DRAW, &[], &logits, 2, index, 0.01).pass); + // far from a boundary the band changes nothing + let index = index_with_uniform(DRAW.seed, 0.45..0.55); + assert!(!judge(DRAW, &[], &logits, 0, index, 0.01).pass); + assert!(judge(DRAW, &[], &logits, 1, index, 0.01).exact); +} + +#[test] +fn the_draw_is_over_the_kept_candidates_alone() { + // top-k 2 keeps tokens 1 and 3: weights 2 and 1, one boundary at 2/3 + let logits = vec![-5.0, 2f64.ln(), -6.0, 0.0]; + let filters = [Filter::TopK(2)]; + let low = index_with_uniform(DRAW.seed, 0.1..0.6); + let high = index_with_uniform(DRAW.seed, 0.7..0.95); + assert!(judge(DRAW, &filters, &logits, 1, low, 0.0).exact); + assert!(judge(DRAW, &filters, &logits, 3, high, 0.0).exact); + assert!(!judge(DRAW, &filters, &logits, 3, low, 0.0).pass); + // a token the filters drop is not picked at any uniform + for index in [low, high] { + assert!(!judge(DRAW, &filters, &logits, 0, index, 0.0).pass); + assert!(!judge(DRAW, &filters, &logits, 2, index, 0.0).pass); + } +} + +#[test] +fn a_candidate_the_band_may_keep_or_drop_widens_the_interval() { + // top-k 3 over four logits, the last two a hair apart: the node may + // have kept either with the two best + let logits = vec![3.0, 2.0, 0.0, 0.0005]; + let filters = [Filter::TopK(3)]; + // on these logits token 3 is kept, and picked from about 0.965 up + let index = index_with_uniform(DRAW.seed, 0.97..0.999); + let kept = judge(DRAW, &filters, &logits, 3, index, 0.0); + assert!(kept.exact, "{kept:?}"); + // token 2 is dropped on them, and kept within a band of 1e-3 + assert!(!judge(DRAW, &filters, &logits, 2, index, 0.0).pass); + let other = judge(DRAW, &filters, &logits, 2, index, 1e-3); + assert!(other.pass && !other.exact, "{other:?}"); + // the best tokens are kept either way: the best one's interval still + // ends near e/(e+1), far below the uniform + let best = judge(DRAW, &filters, &logits, 0, index, 1e-3); + assert!(!best.pass && best.upper < 0.74, "{best:?}"); +} + +#[test] +fn the_temperature_scales_the_weights_and_the_band() { + // at temperature 0.5 the weights are 1, 4, 1: boundaries at 1/6 and 5/6 + let draw = IndexedDraw { + temperature: 0.5, + ..DRAW + }; + let logits = three(); + let index = index_with_uniform(draw.seed, 0.20..0.24); + let verdict = judge(draw, &[], &logits, 1, index, 0.0); + assert!(verdict.exact, "{verdict:?}"); + assert!((verdict.lower - 1.0 / 6.0).abs() < 1e-12); + assert!((verdict.upper - 5.0 / 6.0).abs() < 1e-12); + assert!(!judge(DRAW, &[], &logits, 1, index, 0.0).pass); +} + +#[test] +fn the_chain_keeps_what_the_runtime_keeps() { + // best first: weights 8, 4, 2, 1, 1 of 16 + let sorted: Vec = [8.0f64, 4.0, 2.0, 1.0, 1.0] + .iter() + .map(|w| w.ln()) + .collect(); + assert_eq!(kept(&sorted, &[]), 5); + assert_eq!(kept(&sorted, &[Filter::TopK(0)]), 5); + assert_eq!(kept(&sorted, &[Filter::TopK(3)]), 3); + // top-p keeps the fewest whose mass reaches p: 8/16, then 12/16 + assert_eq!(kept(&sorted, &[Filter::TopP(0.5)]), 1); + assert_eq!(kept(&sorted, &[Filter::TopP(0.6)]), 2); + assert_eq!(kept(&sorted, &[Filter::TopP(1.0)]), 5); + // after top-k 2 the mass is of the two kept: 8/12 is under 0.7 + assert_eq!(kept(&sorted, &[Filter::TopK(2), Filter::TopP(0.7)]), 2); + assert_eq!(kept(&sorted, &[Filter::TopP(0.7)]), 2); + // min-p keeps a logit within ln(p) of the best + assert_eq!(kept(&sorted, &[Filter::MinP(0.3)]), 2); + assert_eq!(kept(&sorted, &[Filter::MinP(0.0)]), 5); + // a temperature before a filter changes what it sees: at 2.0 the + // weights are their square roots, and 0.3 of the best keeps one more + assert_eq!( + kept(&sorted, &[Filter::Temperature(2.0), Filter::MinP(0.3)]), + 5 + ); +} + +#[test] +fn a_whole_vocabulary_is_judged() { + // every token kept, as with no filter at a temperature of 1 + let n = 150_000usize; + let logits: Vec = (0..n).map(|i| ((i * 7919) % 1000) as f64 / 100.0).collect(); + let index = 3; + let u = uniform(DRAW.seed, index); + let weights: Vec = logits.iter().map(|l| (l - 9.99).exp()).collect(); + let total: f64 = weights.iter().sum(); + let mut running = 0.0; + let picked = weights + .iter() + .position(|w| { + running += w; + running > u * total + }) + .expect("a picked token"); + assert!(judge(DRAW, &[], &logits, picked, index, 0.0).exact); + assert!(!judge(DRAW, &[], &logits, picked + 1, index, 0.0).pass); + assert!(!judge(DRAW, &[], &logits, picked - 1, index, 0.0).pass); + // with filters and a band: the search for the kept sets ends + let filters = [Filter::TopK(0), Filter::TopP(0.95), Filter::MinP(0.01)]; + let verdict = judge(DRAW, &filters, &logits, picked, index, 1e-2); + assert!(verdict.lower <= verdict.upper, "{verdict:?}"); +} + +#[test] +fn top_p_cuts_where_the_runtime_cuts_in_f32() { + // one likely token first and a long tail of tokens of weight 4e-8: in + // f32, in token id order, each tail weight is under half an ulp of the + // running sum, so llama.cpp's softmax drops them all and gives the + // first token a probability of 1. In f64 it has 0.992, under the top-p + // of 0.995, and the tail would be kept. + let mut logits = vec![-17.0; 200_000]; + logits[0] = 0.0; + let filters = [Filter::TopP(0.995)]; + let index = index_with_uniform(DRAW.seed, 0.996..1.0); + let verdict = judge(DRAW, &filters, &logits, 0, index, 0.0); + assert!(verdict.pass && verdict.exact, "{verdict:?}"); + // the node kept the first token alone: a tail token is not its pick, + // and passes only as the f64 reading, a draw the verdict counts + let tail = judge(DRAW, &filters, &logits, 150_000, index, 0.0); + assert!(!tail.exact, "{tail:?}"); +} + +#[test] +fn weights_that_overflow_leave_the_runtime_the_last_candidate() { + // at a temperature of 1e-39 every positive logit becomes infinite in + // f32: the runtime's weights are all 0, and its draw takes the last + // kept candidate in token id order + let draw = IndexedDraw { + temperature: 1e-39, + ..DRAW + }; + let logits = vec![3.0, 1.0, 2.0]; + for index in 0..20 { + let verdict = judge(draw, &[], &logits, 2, index, 0.0); + assert!(verdict.pass && verdict.exact, "{verdict:?}"); + } + // after top-k 2 the last kept candidate is token 2 still; after top-k + // 1 it is the best one + assert!(judge(draw, &[Filter::TopK(1)], &logits, 0, 3, 0.0).exact); + // a temperature that does not overflow takes the best + let cold = IndexedDraw { + temperature: 1e-3, + ..DRAW + }; + assert!(judge(cold, &[], &logits, 0, 3, 0.0).exact); +} diff --git a/crates/skippy-receipts/src/head/every_row.rs b/crates/skippy-receipts/src/head/every_row.rs new file mode 100644 index 00000000..8e719d4f --- /dev/null +++ b/crates/skippy-receipts/src/head/every_row.rs @@ -0,0 +1,309 @@ +//! The output head check without a head key: the logits the node opened, +//! against every row of the claimed output matrix. +//! +//! A recheck of evidence has no head key, since the key is one client's +//! secret. It reads the whole output matrix instead, which shows the same +//! thing with no secret: for opened logits `y` at a residual whose normed +//! input is `x`, an honest node has `y = W · x` on every row, up to the +//! rounding of its backend's kernel ([`crate::activation_rounding`]). Then +//! the check judges the token on `y`, as the check with a key does +//! ([`super::key`]). +//! +//! The two checks are meant to give one verdict: +//! +//! - Both judge the token on the node's own logits. Neither judges it on +//! logits it computed with other rounding. +//! - Both run the same row check on the same drawn rows and the sampled +//! token's. +//! - A key's vectors hold a sign per row, so one changed logit moves the +//! key's error by exactly its size. The error here is the norm of the +//! difference over all rows, which is at least that size. So a logit +//! moved past [`EVERY_ROW_TOLERANCE`] of the logits' norm fails both, +//! and this check also fails changes spread over many rows that a key +//! catches only with some probability. +//! +//! A value of the activation within a few ulps of a rounding boundary may +//! round the other way on the node ([`rounding_flips`]). The key check +//! finds those flips from its key. This check finds them from a few rows +//! ([`GUIDE_ROWS`]) and then confirms them on every row. When that fails, +//! it looks once more, at the rows that were furthest off, since a flip +//! shows on every row its weight column is not zero in. The choice of +//! flips gives a node nothing: the logits must still be within the +//! tolerance of `W` times an activation at most two flips from the +//! profile's, on every row. + +use anyhow::{Context, Result}; + +use super::key::KEY_TOLERANCE; +use super::opened_logits::{ + self, LogitsCheck, Opened, checked_rows, dot, drawn_rows, picked_rows, scale_candidates, + shown_scale, unbiased, +}; +use super::reasoning_budget::Forcing; +use super::sampling::TokenRule; +use super::{HeadVerdict, OutputHead, judge_position, verdict}; +use crate::activation_rounding::Profile; +use crate::audit; +use crate::audit::rounding_flips; +use crate::error_bound::within; +use crate::rounding_profiles::BackendFamily; +use crate::weights::WeightFile; +use crate::wire::{HeadOpening, Receipt}; + +/// The check fails above this error, relative to the logits' norm: the +/// norm of the difference between the opened logits and the claimed +/// head's, over every row. It is the head key's tolerance, so a logit the +/// key check refuses is refused here. +/// +/// Honest Qwen3-4B Q8_0 logits were within 4.3e-7 on CPU (132 positions) +/// and within 1.6e-7 on CUDA (36 positions). +pub(crate) const EVERY_ROW_TOLERANCE: f64 = KEY_TOLERANCE; + +/// Rows that show which rounding flips the node took, besides the rows of +/// the row check. One flip moves every row by its weight in one column, so +/// a few rows tell the flips apart. +const GUIDE_ROWS: usize = 48; + +/// One profile's reading of a position: the activation the node's kernel +/// met by it, and the logits the matrix alone gave. +struct Reading { + profile: Profile, + /// The profile's activation, with the rounding flips the guide rows + /// show. + activation: Vec, + flips: usize, + /// The opened logits without the scale and the bias. + unbiased: Vec, + /// The worst difference left on the guide rows. + guide_error: f64, +} + +/// What reading one position's logits needs besides them. +struct Reader<'a> { + weights: &'a WeightFile, + head: &'a OutputHead, + profiles: &'a [Profile], + scales: &'a [f64], +} + +impl Reader<'_> { + /// The reading of `opened` that fits the guide rows best. + fn read(&self, opened: &Opened, guide: &[u64]) -> Result { + let rows = weight_rows(self.weights, &self.head.weight, guide)?; + self.profiles + .iter() + .map(|&profile| self.read_as(profile, opened, &rows)) + .reduce(|best, next| { + if next.guide_error < best.guide_error { + next + } else { + best + } + }) + .context("no rounding profile to check the logits with") + } + + /// The reading of `opened` under one profile. + fn read_as(&self, profile: Profile, opened: &Opened, rows: &[(usize, Vec)]) -> Reading { + let mut activation = profile.apply(&opened.activation); + let reference: Vec<(usize, f64)> = rows + .iter() + .map(|(r, w)| (*r, dot(w, &activation) + self.head.bias_of(*r))) + .collect(); + let scale = shown_scale(&reference, &opened.logits, self.scales); + let unbiased = unbiased(self.head, &opened.logits, scale); + let residuals: Vec = rows + .iter() + .map(|(r, w)| f64::from(unbiased[*r]) - dot(w, &activation)) + .collect(); + let flips = rounding_flips::flips(profile, &opened.activation, &activation); + let effects: Vec> = flips + .iter() + .map(|flip| { + rows.iter() + .map(|(_, w)| flip.changes.iter().map(|&(i, d)| w[i] * d).sum()) + .collect() + }) + .collect(); + let (taken, guide_error) = rounding_flips::best_explanation(&residuals, &effects); + for flip in taken.iter().map(|&f| &flips[f]) { + for &(i, change) in &flip.changes { + activation[i] += change; + } + } + Reading { + profile, + activation, + flips: taken.len(), + unbiased, + guide_error, + } + } +} + +/// Rows of `weight`, by index. +fn weight_rows(weights: &WeightFile, weight: &str, rows: &[u64]) -> Result)>> { + rows.iter() + .map(|&row| Ok((row as usize, weights.row(weight, row)?))) + .collect() +} + +/// The check of one reading against the matrix's `products` with its +/// activation, one per row, and against the `checked` rows of the row +/// check. +fn check(reading: &Reading, products: &[f64], checked: &[(usize, Vec)]) -> LogitsCheck { + let difference: f64 = reading + .unbiased + .iter() + .zip(products) + .map(|(&y, reference)| (f64::from(y) - reference).powi(2)) + .sum(); + let error = difference.sqrt() / opened_logits::norm(&reading.unbiased); + let rows: Vec<(usize, &[f64])> = checked.iter().map(|(r, w)| (*r, w.as_slice())).collect(); + let row_error = audit::column_error(&rows, &reading.activation, &reading.unbiased); + LogitsCheck { + error, + row_error, + profile: reading.profile.name(), + rounding_flips: reading.flips, + every_row: true, + pass: within(error, EVERY_ROW_TOLERANCE) && within(row_error, audit::TOLERANCE), + } +} + +/// One head position and what its checks read. +struct Position { + position: u32, + sampled: i32, + opened: Opened, + /// The rows of the row check, with their weights. + checked: Vec<(usize, Vec)>, +} + +/// The `count` rows where the logits of `reading` are furthest from the +/// matrix's `products` with its activation. +fn furthest_rows(reading: &Reading, products: &[f64], count: usize) -> Vec { + let mut rows: Vec<(f64, u64)> = reading + .unbiased + .iter() + .zip(products) + .enumerate() + .map(|(row, (&y, reference))| ((f64::from(y) - reference).abs(), row as u64)) + .collect(); + rows.sort_unstable_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + rows.truncate(count); + rows.into_iter().map(|(_, row)| row).collect() +} + +/// The checks of `readings`, one per position, in one pass over the +/// matrix, with the matrix's products with each reading's activation. +fn check_all( + reader: &Reader<'_>, + positions: &[&Position], + readings: &[Reading], +) -> Result<(Vec, Vec>)> { + let activations: Vec> = readings.iter().map(|r| r.activation.clone()).collect(); + let products = reader.head.products(reader.weights, &activations)?; + let checks = readings + .iter() + .zip(&products) + .zip(positions) + .map(|((reading, products), p)| check(reading, products, &p.checked)) + .collect(); + Ok((checks, products)) +} + +/// Reads the positions that `checks` refused once more, from the rows +/// where their logits were furthest from the `products` of the first pass, +/// and keeps a check that comes out less far off. +fn check_refused_again( + reader: &Reader<'_>, + positions: &[Position], + readings: &[Reading], + products: &[Vec], + checks: &mut [LogitsCheck], +) -> Result<()> { + let refused: Vec = (0..checks.len()).filter(|&i| !checks[i].pass).collect(); + if refused.is_empty() { + return Ok(()); + } + let mut again = Vec::with_capacity(refused.len()); + for &i in &refused { + let guide = furthest_rows(&readings[i], &products[i], GUIDE_ROWS); + again.push(reader.read(&positions[i].opened, &guide)?); + } + let of: Vec<&Position> = refused.iter().map(|&i| &positions[i]).collect(); + let (rechecked, _) = check_all(reader, &of, &again)?; + for (&i, check) in refused.iter().zip(rechecked) { + if check.pass || within(check.error, checks[i].error) { + checks[i] = check; + } + } + Ok(()) +} + +/// Checks the logits the final stage on `backend` opened at each head +/// position against every row of the claimed output matrix, and the token +/// sampled from each on those logits by `rule`. The rows of the row check come from +/// `rows_seed`, as an audit draws them. +/// +/// A position without logits is the node's fault, as it is for an audit: +/// a node may not leave them out to be judged on other logits. So is a +/// residual or a logit vector of the wrong length, or one that holds a +/// value that is not a number ([`crate::node_fault::NodeFault`]). Any +/// other error is the auditor's. +pub fn check_head_on_every_row( + weights: &WeightFile, + receipt: &Receipt, + openings: &[HeadOpening], + backend: &str, + rows_seed: &[u8], + (rule, forcing): (&TokenRule, &Forcing), +) -> Result { + let head = OutputHead::from_weights(weights)?; + let tensor = weights.tensor(&head.weight)?; + let rows = tensor.rows(); + let family = BackendFamily::checked(backend)?; + let reader = Reader { + weights, + head: &head, + profiles: audit::checked_profiles(family, tensor.ggml_type)?, + scales: &scale_candidates(weights), + }; + OutputHead::prefetch(weights)?; + let picked = picked_rows(rows_seed, rows); + let extra = drawn_rows(rows_seed, "rows/output-head-flips", GUIDE_ROWS, rows); + let mut positions = Vec::with_capacity(openings.len()); + let mut readings = Vec::with_capacity(openings.len()); + for opening in openings { + let sampled = receipt + .sampled_after(opening.position) + .with_context(|| format!("no token was sampled at position {}", opening.position))?; + let opened = opened_logits::read(&head, rows, opening)?; + let checked = checked_rows(&picked, sampled, rows); + let guide: Vec = checked.iter().chain(&extra).copied().collect(); + readings.push(reader.read(&opened, &guide)?); + positions.push(Position { + position: opening.position, + sampled, + opened, + checked: weight_rows(weights, &head.weight, &checked)?, + }); + } + let all: Vec<&Position> = positions.iter().collect(); + let (mut checks, products) = check_all(&reader, &all, &readings)?; + check_refused_again(&reader, &positions, &readings, &products, &mut checks)?; + let mut verdicts = Vec::with_capacity(positions.len()); + for (p, checked) in positions.iter().zip(checks) { + let logits: Vec = p.opened.logits.iter().map(|&v| f64::from(v)).collect(); + // the opened logits are the ones the node sampled from, scale and all + let mut judged = judge_position(rule, forcing, p.position, &logits, p.sampled)?; + judged.pass &= checked.pass; + judged.logits = Some(checked); + verdicts.push(judged); + } + Ok(verdict(verdicts)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/head/every_row/tests.rs b/crates/skippy-receipts/src/head/every_row/tests.rs new file mode 100644 index 00000000..9f3b662d --- /dev/null +++ b/crates/skippy-receipts/src/head/every_row/tests.rs @@ -0,0 +1,479 @@ +use super::*; +use crate::ggml_types::{GGML_F32, GGML_Q8_0}; +use crate::head::{check_computed_head, check_head}; +use crate::node_fault::NodeFault; +use crate::weights::{MetaValue, test_gguf}; +use crate::wire::{RECEIPT_VERSION, StageCommitment, encode_f32}; + +const ROWS: usize = 64; +/// One q8 block. +const WIDTH: usize = 32; +const SEED: &[u8] = b"rows"; + +/// The weights of the toy output matrix, as q8_0 steps of 1. Tokens 0 and +/// 1 are far ahead of the rest. Token 1's row is token 0's plus a part +/// that nearly cancels on [`residual`]: 127 on values 1 to 16, and -127 on +/// values 17 and 18. +fn steps() -> Vec<[i8; WIDTH]> { + let mut rows: Vec<[i8; WIDTH]> = (0..ROWS) + .map(|r| std::array::from_fn(|i| ((r * 7 + i * 3) % 5) as i8 - 2)) + .collect(); + rows[0] = [0; WIDTH]; + rows[0][0] = 127; + rows[1] = rows[0]; + rows[1][1..=16].fill(127); + rows[1][17] = -127; + rows[1][18] = -127; + rows +} + +/// A toy model with the q8_0 output matrix `steps`, which a CPU node meets +/// with a q8 activation. It divides its logits by `logit_scale` when +/// given. +fn model_of(steps: &[[i8; WIDTH]], logit_scale: Option) -> WeightFile { + model_with(steps, logit_scale, Vec::new()) +} + +/// [`model_of`] with more metadata. +fn model_with( + steps: &[[i8; WIDTH]], + logit_scale: Option, + extra: Vec<(&str, MetaValue)>, +) -> WeightFile { + let mut meta = vec![ + ("general.architecture", MetaValue::Str("toy".into())), + ( + "toy.attention.layer_norm_rms_epsilon", + MetaValue::Float(0.0), + ), + ]; + if let Some(scale) = logit_scale { + meta.push(("toy.logit_scale", MetaValue::Float(scale))); + } + meta.extend(extra); + let (mut bytes, _) = test_gguf::header( + &meta, + &[ + ("output_norm.weight", vec![WIDTH as u64], GGML_F32), + ( + "token_embd.weight", + vec![WIDTH as u64, ROWS as u64], + GGML_Q8_0, + ), + ], + ); + for _ in 0..WIDTH { + bytes.extend(1.0f32.to_le_bytes()); + } + for row in steps { + bytes.extend(half::f16::from_f32(1.0).to_le_bytes()); + bytes.extend(row.iter().map(|&step| step as u8)); + } + WeightFile::open(Box::new(test_gguf::Memory(bytes))).expect("a test GGUF") +} + +fn model() -> WeightFile { + model_of(&steps(), None) +} + +/// A residual whose q8 activation has these steps: 127 at values 0 and +/// 17, 37 at value 18, and 10.49 at values 1 to 16, which a q8 kernel +/// rounds down to 10. On the unrounded activation token 1 leads token 0 +/// by 16 × 127 × 0.49 less the 508 that the rounded one leaves token 0 +/// ahead by. +fn residual() -> Vec { + let mut x = vec![1.0f32; WIDTH]; + x[0] = 127.0; + x[1..=16].fill(10.49); + x[17] = 127.0; + x[18] = 37.0; + x +} + +/// A turn of two positions whose second token was sampled from the first. +fn receipt(sampled: i32) -> Receipt { + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 2, + tokens: vec![0, sampled], + generation_start: 1, + final_token: Some(1), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 1, + root: String::new(), + leaf_count: 0, + backend: "CPU".into(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: None, + } +} + +/// The activation the output matrix of `weights` meets at `residual`, as +/// the client norms it and as a CPU node's q8 kernel rounds it. +fn activations(weights: &WeightFile, residual: &[f32]) -> (Vec, Vec) { + let head = OutputHead::from_weights(weights).unwrap(); + let x: Vec = head + .norm + .apply(residual) + .unwrap() + .iter() + .map(|&v| v as f32) + .collect(); + let rounded = Profile::CpuQ8.apply(&x); + (x, rounded) +} + +/// The logits a node computes from `activation`. +fn logits_of(weights: &WeightFile, activation: &[f64]) -> Vec { + let head = OutputHead::from_weights(weights).unwrap(); + head.products(weights, &[activation.to_vec()]) + .unwrap() + .remove(0) + .iter() + .map(|&v| v as f32) + .collect() +} + +/// The logits an honest CPU node opens at `residual`. +fn honest(weights: &WeightFile, residual: &[f32]) -> Vec { + logits_of(weights, &activations(weights, residual).1) +} + +fn best(logits: &[f32]) -> i32 { + (0..logits.len()) + .max_by(|&a, &b| logits[a].total_cmp(&logits[b])) + .unwrap() as i32 +} + +fn opening(residual: &[f32], logits: Option<&[f32]>) -> HeadOpening { + HeadOpening { + position: 0, + residual: encode_f32(residual), + path: Vec::new(), + logits: logits.map(encode_f32), + } +} + +fn check_of(weights: &WeightFile, residual: &[f32], logits: &[f32], sampled: i32) -> HeadVerdict { + check_head_on_every_row( + weights, + &receipt(sampled), + &[opening(residual, Some(logits))], + "CPU", + SEED, + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap() +} + +fn norm_of(logits: &[f32]) -> f32 { + logits.iter().map(|v| v * v).sum::().sqrt() +} + +#[test] +fn an_honest_token_passes_where_the_clients_own_rounding_gives_another() { + let weights = model(); + let logits = honest(&weights, &residual()); + // the node's kernel rounds the activation, and token 0 leads + assert_eq!(best(&logits), 0); + let verdict = check_of(&weights, &residual(), &logits, 0); + assert!(verdict.pass && verdict.ties == 0, "{verdict:?}"); + let position = &verdict.positions[0]; + assert_eq!((position.best, position.within_band), (0, false)); + let checked = position.logits.unwrap(); + assert!(checked.every_row && checked.pass, "{checked:?}"); + assert!(checked.error < 1e-6 && checked.row_error < 1e-6); + assert_eq!((checked.profile, checked.rounding_flips), ("cpu_q8_0", 0)); + + // logits computed without that rounding put token 1 ahead by far more + // than the tie band, so a check that judged on them refused the honest + // node + let computed = check_computed_head( + &weights, + &receipt(0), + &[opening(&residual(), Some(&logits))], + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap(); + assert_eq!(computed.positions[0].best, 1); + assert!(-computed.positions[0].margin > 10.0 * computed.positions[0].band); + assert!(!computed.pass); + + // a recheck judges the node's logits + let rechecked = check_head( + &weights, + &receipt(0), + &[opening(&residual(), Some(&logits))], + "CPU", + SEED, + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap(); + assert_eq!(rechecked, verdict); + // and it holds the node to them: token 1 is not their best + assert!(!check_of(&weights, &residual(), &logits, 1).pass); +} + +#[test] +fn a_logit_moved_past_the_tolerance_fails() { + let weights = model(); + let logits = honest(&weights, &residual()); + let norm = norm_of(&logits); + // a row that the row check does not read + let unread = (2..ROWS) + .find(|&row| !picked_rows(SEED, ROWS as u64).contains(&(row as u64))) + .unwrap(); + for (moved_by, passes) in [(0.1, true), (3.0, false), (-3.0, false), (1e4, false)] { + let mut changed = logits.clone(); + changed[unread] += moved_by * EVERY_ROW_TOLERANCE as f32 * norm; + let verdict = check_of(&weights, &residual(), &changed, 0); + let checked = verdict.positions[0].logits.unwrap(); + assert_eq!(checked.pass, passes, "{moved_by}: {checked:?}"); + assert_eq!(verdict.pass, passes, "{moved_by}"); + if !passes { + // only the difference over every row shows it + assert!(checked.error > EVERY_ROW_TOLERANCE, "{checked:?}"); + } + } + // a logit moved to make another token the best fails as well, though + // that token is then the best of the opened logits + let mut steered = logits.clone(); + steered[1] = steered[0] + 1.0; + let verdict = check_of(&weights, &residual(), &steered, 1); + assert!(!verdict.pass && !verdict.positions[0].logits.unwrap().pass); + // and so does every logit moved by the same small factor + let scaled: Vec = logits.iter().map(|v| v * 1.0001).collect(); + assert!(!check_of(&weights, &residual(), &scaled, 0).pass); +} + +fn fault(weights: &WeightFile, opening: HeadOpening) -> String { + let error = check_head_on_every_row( + weights, + &receipt(0), + &[opening], + "CPU", + SEED, + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + format!("{error:#}") +} + +#[test] +fn logits_left_out_or_malformed_are_the_nodes_fault() { + let weights = model(); + let logits = honest(&weights, &residual()); + // an audit with a key blames the node for these too + assert!(fault(&weights, opening(&residual(), None)).contains("opened no logits")); + assert!(fault(&weights, opening(&residual(), Some(&logits[1..]))).contains("63 logits for 64")); + let mut broken = logits.clone(); + broken[5] = f32::NAN; + assert!(fault(&weights, opening(&residual(), Some(&broken))).contains("not a number")); + assert!(fault(&weights, opening(&residual()[1..], Some(&logits))).contains("output norm")); + // a token outside the vocabulary + let error = check_head_on_every_row( + &weights, + &receipt(ROWS as i32), + &[opening(&residual(), Some(&logits))], + "CPU", + SEED, + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + // a backend without rounding profiles cannot be checked, which is not + // the node's fault + let error = check_head_on_every_row( + &weights, + &receipt(0), + &[opening(&residual(), Some(&logits))], + "Metal", + SEED, + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} + +#[test] +fn logits_at_the_models_scale_pass_and_at_another_fail() { + let scaled = model_of(&steps(), Some(4.0)); + let logits = honest(&scaled, &residual()); + // some architectures divide by the scale and some multiply + for factor in [0.25f32, 4.0] { + let opened: Vec = logits.iter().map(|v| v * factor).collect(); + let verdict = check_of(&scaled, &residual(), &opened, 0); + assert!(verdict.pass, "{factor}: {verdict:?}"); + } + let other: Vec = logits.iter().map(|v| v * 2.0).collect(); + assert!(!check_of(&scaled, &residual(), &other, 0).pass); + // a model without a scale takes its logits as they are + let unscaled = model(); + let opened: Vec = logits.iter().map(|v| v * 0.25).collect(); + assert!(!check_of(&unscaled, &residual(), &opened, 0).pass); +} + +/// The node's activation when it rounded value `index` the other way, with +/// the residual that puts that value on a rounding boundary. +fn flipped(weights: &WeightFile, index: usize) -> (Vec, Vec) { + let mut residual = residual(); + // halfway between steps 10 and 11 + residual[index] = 10.5; + let (x, mut rounded) = activations(weights, &residual); + let flip = rounding_flips::flips(Profile::CpuQ8, &x, &rounded) + .into_iter() + .find(|flip| flip.changes.len() == 1 && flip.changes[0].0 == index) + .expect("the value lies on a boundary"); + rounded[index] += flip.changes[0].1; + (residual, rounded) +} + +#[test] +fn a_rounding_the_node_took_the_other_way_passes() { + let weights = model(); + let (tied, node) = flipped(&weights, 20); + let logits = logits_of(&weights, &node); + let verdict = check_of(&weights, &tied, &logits, best(&logits)); + let checked = verdict.positions[0].logits.unwrap(); + assert!(verdict.pass && checked.error < 1e-6, "{checked:?}"); + assert_eq!(checked.rounding_flips, 1); + // the same logits at a residual without that boundary are too far off + let plain = check_of(&weights, &residual(), &logits, best(&logits)); + assert!(!plain.pass && plain.positions[0].logits.unwrap().rounding_flips == 0); +} + +#[test] +fn a_flip_that_only_other_rows_show_is_found_from_them() { + // value 20 has a weight in one row alone, which no guide row is + let guide: Vec = picked_rows(SEED, ROWS as u64) + .into_iter() + .chain(drawn_rows( + SEED, + "rows/output-head-flips", + GUIDE_ROWS, + ROWS as u64, + )) + .collect(); + let lone = (2..ROWS) + .find(|&row| !guide.contains(&(row as u64))) + .expect("a row outside the guide rows"); + let mut steps = steps(); + for (row, weights) in steps.iter_mut().enumerate() { + weights[20] = if row == lone { 100 } else { 0 }; + } + let weights = model_of(&steps, None); + let (tied, node) = flipped(&weights, 20); + let logits = logits_of(&weights, &node); + let verdict = check_of(&weights, &tied, &logits, 0); + let checked = verdict.positions[0].logits.unwrap(); + assert!(verdict.pass, "{checked:?}"); + assert_eq!(checked.rounding_flips, 1); +} + +#[test] +fn a_soft_capped_models_tokens_are_not_judged() { + // its opened logits are not the matrix's product, and logits the + // client computes lack the node's rounding: judged on them, the honest + // token 0 here failed + let capped = model_with( + &steps(), + None, + vec![("toy.final_logit_softcapping", MetaValue::Float(30.0))], + ); + let no_end = |_: i32| -> Result { Ok(false) }; + let rule = crate::head::token_rule_for(&capped, &receipt(0), &no_end); + assert!(matches!(rule, TokenRule::Unjudged(_)), "{rule:?}"); + let logits = honest(&model(), &residual()); + let verdict = check_head( + &capped, + &receipt(0), + &[opening(&residual(), Some(&logits))], + "CPU", + SEED, + (&rule, &Forcing::Free), + ) + .unwrap(); + assert!(verdict.pass, "{verdict:?}"); + assert!(verdict.positions.iter().all(|p| !p.judged)); + // a residual that does not fit the head is still the node's fault + let error = check_head( + &capped, + &receipt(0), + &[opening(&[1.0; 3], None)], + "CPU", + SEED, + (&rule, &Forcing::Free), + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); +} + +#[test] +fn suppressed_and_ignored_end_tokens_are_taken_out_before_the_judgement() { + let logits = honest(&model(), &residual()); + assert_eq!(best(&logits), 0); + let no_end = |_: i32| -> Result { Ok(false) }; + // the model suppresses token 0: an honest node took the next best + let suppressing = model_with( + &steps(), + None, + vec![("tokenizer.ggml.suppress_tokens", MetaValue::Tokens(vec![0]))], + ); + let rule = crate::head::token_rule_for(&suppressing, &receipt(1), &no_end); + let check = |weights: &WeightFile, rule: &TokenRule, sampled: i32| { + check_head_on_every_row( + weights, + &receipt(sampled), + &[opening(&residual(), Some(&logits))], + "CPU", + SEED, + (rule, &Forcing::Free), + ) + .unwrap() + }; + assert!(check(&suppressing, &rule, 1).pass); + assert!(!check(&suppressing, &rule, 0).pass); + // a turn that ignores its end loses the end tokens the same way + let mut ignoring = receipt(1); + ignoring.binding = Some(crate::turn::TurnBinding { + client_key: String::new(), + parent: None, + runtime: String::new(), + sampler: turn_sampler(serde_json::json!({"temperature": 0.0, "ignore_eos": true})), + node_key: String::new(), + turn_root: String::new(), + signature: String::new(), + }); + let end = |token: i32| -> Result { Ok(token == 0) }; + let rule = crate::head::token_rule_for(&model(), &ignoring, &end); + assert!(check(&model(), &rule, 1).pass, "{rule:?}"); + assert!(!check(&model(), &rule, 0).pass); + // a vocabulary that cannot name them leaves the tokens unjudged + let unknown = |_: i32| -> Result { anyhow::bail!("no vocabulary") }; + let rule = crate::head::token_rule_for(&model(), &ignoring, &unknown); + assert!(matches!(rule, TokenRule::Unjudged(_))); +} + +/// A sampled statement of the default chain with `overrides`. +fn turn_sampler(overrides: serde_json::Value) -> String { + let mut p = serde_json::json!({ + "seed": 7, "draw": null, + "samplers": ["top_k", "top_p", "min_p", "temperature"], + "temperature": 0.8, "top_k": 40, "top_p": 0.95, "min_p": 0.05, + "logit_bias": [], "grammar": null, + }); + for (k, v) in overrides.as_object().unwrap() { + p[k] = v.clone(); + } + crate::turn::sampled(&p) +} diff --git a/crates/skippy-receipts/src/head/key.rs b/crates/skippy-receipts/src/head/key.rs new file mode 100644 index 00000000..b2bdee7b --- /dev/null +++ b/crates/skippy-receipts/src/head/key.rs @@ -0,0 +1,389 @@ +//! The output head check with a head key: the client checks the logits the +//! node opened instead of computing the whole output matrix. +//! +//! The key holds [`KEY_VECTORS`] secret ±1 vectors `r` over the vocabulary +//! and, for each, `rᵀW` over the output matrix `W`: a few vectors of the +//! model width, built in one pass over the matrix. For opened logits `y` +//! at a residual whose normed input is `x`, an honest node has +//! `r · y = (rᵀW) · x` up to rounding (Freivalds). A node that changes any +//! logit by more than the rounding shows up, since it does not know `r`. +//! The check also compares a few rows of `W` with `y` like any matmul, +//! always including the sampled token's, and judges the greedy choice on +//! `y` itself. +//! +//! The key must stay secret, so it lives only on the client. Someone who +//! rechecks evidence without it compares the logits with every row of the +//! output matrix instead ([`super::every_row`]), which accepts the logits +//! this check accepts. + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use super::opened_logits::{ + self, LogitsCheck, checked_rows, dot, picked_rows, scale_candidates, shown_scale, unbiased, +}; +use super::reasoning_budget::Forcing; +use super::sampling::TokenRule; +use super::{HeadVerdict, OutputHead, judge_position, verdict}; +use crate::activation_rounding::Profile; +use crate::audit; +use crate::audit::rounding_flips::{self, Flip}; +use crate::commitment::hex_array; +use crate::error_bound::within; +use crate::rounding_profiles::BackendFamily; +use crate::weights::WeightFile; +use crate::wire::{HeadOpening, Receipt}; + +/// Secret vectors per key. A change of a logit that another change +/// cancels in every vector needs two rows whose signs agree in all of +/// them: 1 in 65,536 for a pair of rows the node picks blind. +pub(crate) const KEY_VECTORS: usize = 16; +/// The layout of a key file. A file of another layout, such as the first +/// one, which had 4 vectors and no version, is built again: it is never +/// read as this one. +pub(crate) const KEY_VERSION: u32 = 2; +/// The key check fails above this error, relative to the logits' norm. +/// Honest Qwen3-4B Q8_0 logits on CUDA were within 1.5e-7. A change that +/// steers the greedy choice must move a logit past the tie band, about +/// 1e-2 of the logits' RMS, or some 3e-5 of their norm over a vocabulary +/// of 150k, so it shows up above this. +pub(crate) const KEY_TOLERANCE: f64 = 1e-5; + +/// A client's secret head key for one claimed model. +#[derive(Clone, Serialize, Deserialize, PartialEq)] +pub struct HeadKey { + /// [`KEY_VERSION`]. A file without it does not parse. + version: u32, + /// The output matrix the key is for, and its shape and type. + pub weight: String, + pub dims: Vec, + pub ggml_type: u32, + /// Hex seed of the secret signs. + seed: String, + /// Per vector, `rᵀW` as base64 little-endian f64. + vectors: Vec, +} + +/// The key without its secrets: a log line or a panic message must not +/// hold the seed, or the vectors, from which the signs follow. +impl std::fmt::Debug for HeadKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HeadKey") + .field("weight", &self.weight) + .field("dims", &self.dims) + .field("ggml_type", &self.ggml_type) + .finish_non_exhaustive() + } +} + +/// The key in a usable form. +struct Key { + /// Per row, the sign bits of the vectors. + signs: Vec, + vectors: Vec>, +} + +impl HeadKey { + /// Builds a key from `seed`, which must be secret and fresh, in one pass + /// over the output matrix. The pass reads the matrix once: a sparse + /// copy does not keep it. + pub fn build(weights: &WeightFile, seed: [u8; 32]) -> Result { + let weight = super::head_weight(weights); + let tensor = weights.tensor(weight)?; + let (rows, width) = (tensor.rows(), usize::try_from(tensor.row_len())?); + let signs = signs(&seed, rows); + let threads = std::thread::available_parallelism() + .map_or(1, std::num::NonZero::get) + .min(16) as u64; + let span = rows.div_ceil(threads).max(1); + let parts = std::thread::scope(|scope| { + let handles: Vec<_> = (0..rows) + .step_by(span as usize) + .map(|first| { + let signs = &signs; + scope.spawn(move || -> Result>> { + let mut sums = vec![vec![0.0f64; width]; KEY_VECTORS]; + let range = first..(first + span).min(rows); + weights.stream_rows(weight, range, &mut |row, values| { + for (k, sum) in sums.iter_mut().enumerate() { + let r = sign(signs, row, k); + for (s, w) in sum.iter_mut().zip(values) { + *s += r * w; + } + } + })?; + Ok(sums) + }) + }) + .collect(); + handles + .into_iter() + .map(|h| { + h.join() + .unwrap_or_else(|_| bail!("a head key thread panicked")) + }) + .collect::>>() + })?; + let mut vectors = vec![vec![0.0f64; width]; KEY_VECTORS]; + for part in parts { + for (all, sums) in vectors.iter_mut().zip(part) { + for (a, s) in all.iter_mut().zip(sums) { + *a += s; + } + } + } + Ok(Self { + version: KEY_VERSION, + weight: weight.to_owned(), + dims: tensor.dims.clone(), + ggml_type: tensor.ggml_type, + seed: hex::encode(seed), + vectors: vectors.iter().map(|v| encode_f64(v)).collect(), + }) + } + + /// Whether the key is for the output matrix of `weights` and holds a + /// seed and vectors a check can use. A key file that parses but fails + /// this is built again; kept, it would leave the head unchecked for + /// good. + pub fn fits(&self, weights: &WeightFile) -> bool { + let weight = super::head_weight(weights); + weights.tensor(weight).is_ok_and(|t| { + self.version == KEY_VERSION + && self.weight == weight + && t.dims == self.dims + && t.ggml_type == self.ggml_type + && usize::try_from(t.row_len()) + .is_ok_and(|width| self.usable(t.rows(), width).is_ok()) + }) + } + + fn usable(&self, rows: u64, width: usize) -> Result { + let seed = hex_array(&self.seed, "the head key's seed")?; + let vectors = self + .vectors + .iter() + .map(|v| decode_f64(v)) + .collect::>>()?; + let finite = |v: &Vec| v.iter().all(|x| x.is_finite()); + if vectors.len() != KEY_VECTORS || vectors.iter().any(|v| v.len() != width || !finite(v)) { + bail!("the head key does not fit the output matrix"); + } + Ok(Key { + signs: signs(&seed, rows), + vectors, + }) + } +} + +/// Checks the logits the final stage opened at each head position with +/// `key`, and the token sampled from each by `rule`, for a stage on `backend`. The +/// checked rows come from `rows_seed`. +/// +/// A position without logits is the node's fault: a node may not leave +/// them out to be judged on logits the client computes with other +/// rounding. So is a +/// residual or a logit vector of the wrong length, or one that holds a +/// value that is not a number ([`crate::node_fault::NodeFault`]). Any +/// other error is the auditor's. +pub fn check_head_with_key( + weights: &WeightFile, + key: &HeadKey, + receipt: &Receipt, + openings: &[HeadOpening], + backend: &str, + rows_seed: &[u8], + (rule, forcing): (&TokenRule, &Forcing), +) -> Result { + if !key.fits(weights) { + bail!("the head key is for another output matrix"); + } + let head = OutputHead::from_weights(weights)?; + let tensor = weights.tensor(&head.weight)?; + let family = BackendFamily::checked(backend)?; + let profiles = audit::checked_profiles(family, tensor.ggml_type)?; + let usable = key.usable(tensor.rows(), usize::try_from(tensor.row_len())?)?; + let picked = picked_rows(rows_seed, tensor.rows()); + let scales = scale_candidates(weights); + let checker = LogitsChecker { + weights, + head: &head, + key: &usable, + profiles, + scales: &scales, + }; + let mut positions = Vec::with_capacity(openings.len()); + for opening in openings { + let sampled = receipt + .sampled_after(opening.position) + .with_context(|| format!("no token was sampled at position {}", opening.position))?; + let opened = opened_logits::read(&head, tensor.rows(), opening)?; + let rows = checked_rows(&picked, sampled, tensor.rows()); + let check = check_logits(&checker, &opened.activation, &opened.logits, &rows)?; + let as_f64: Vec = opened.logits.iter().map(|&v| f64::from(v)).collect(); + // the opened logits are the ones the node sampled from, scale and all + let mut judged = judge_position(rule, forcing, opening.position, &as_f64, sampled)?; + judged.pass &= check.pass; + judged.logits = Some(check); + positions.push(judged); + } + Ok(verdict(positions)) +} + +/// What checking one position's logits needs besides them. +struct LogitsChecker<'a> { + weights: &'a WeightFile, + head: &'a OutputHead, + key: &'a Key, + profiles: &'a [Profile], + scales: &'a [f64], +} + +fn check_logits(c: &LogitsChecker<'_>, x: &[f32], y: &[f32], rows: &[u64]) -> Result { + let mut ranges: Vec<(u64, u64)> = Vec::with_capacity(rows.len()); + for &row in rows { + ranges.push(c.weights.row_range(&c.head.weight, row)?); + } + c.weights.prefetch(&ranges)?; + let weight_rows = rows + .iter() + .map(|&row| Ok((row as usize, c.weights.row(&c.head.weight, row)?))) + .collect::>>()?; + let mut best: Option = None; + for &profile in c.profiles { + let check = check_profile(c, profile, x, y, &weight_rows); + if best.is_none_or(|b| score(&check) < score(&b)) { + best = Some(check); + } + } + best.context("no rounding profile to check the logits with") +} + +/// [`check_logits`] for one profile. +fn check_profile( + c: &LogitsChecker<'_>, + profile: Profile, + x: &[f32], + y: &[f32], + weight_rows: &[(usize, Vec)], +) -> LogitsCheck { + let mut xp = profile.apply(x); + let reference: Vec<(usize, f64)> = weight_rows + .iter() + .map(|(r, w)| (*r, dot(w, &xp) + c.head.bias_of(*r))) + .collect(); + let scale = shown_scale(&reference, y, c.scales); + // the logits the matrix alone gives, before any scale or bias + let unbiased = unbiased(c.head, y, scale); + let norm = opened_logits::norm(&unbiased); + let residuals: Vec = c + .key + .vectors + .iter() + .enumerate() + .map(|(k, v)| signed_sum(c.key, k, &unbiased) - dot(v, &xp)) + .collect(); + let flips = rounding_flips::flips(profile, x, &xp); + let (taken, key_error) = explained(c.key, &residuals, &flips); + for flip in taken.iter().map(|&f| &flips[f]) { + for &(i, change) in &flip.changes { + xp[i] += change; + } + } + let checked: Vec<(usize, &[f64])> = weight_rows + .iter() + .map(|(r, w)| (*r, w.as_slice())) + .collect(); + let key_error = key_error / norm; + let row_error = audit::column_error(&checked, &xp, &unbiased); + LogitsCheck { + error: key_error, + row_error, + profile: profile.name(), + rounding_flips: taken.len(), + every_row: false, + pass: within(key_error, KEY_TOLERANCE) && within(row_error, audit::TOLERANCE), + } +} + +/// The flips that best explain the key's `residuals`, at most +/// two of them, and the largest residual they leave. +fn explained(key: &Key, residuals: &[f64], flips: &[Flip]) -> (Vec, f64) { + let effects: Vec> = flips + .iter() + .map(|flip| { + key.vectors + .iter() + .map(|v| flip.changes.iter().map(|&(i, d)| v[i] * d).sum()) + .collect() + }) + .collect(); + rounding_flips::best_explanation(residuals, &effects) +} + +/// `r · y` for the key's `k`-th vector `r`. +fn signed_sum(key: &Key, k: usize, y: &[f32]) -> f64 { + y.iter() + .enumerate() + .map(|(i, &u)| sign(&key.signs, i as u64, k) * f64::from(u)) + .sum() +} + +/// How far a key check's `error` was under [`KEY_TOLERANCE`], in whole +/// powers of ten from -3 to 3; below 0 it was over. A report shows this and +/// never the error: a node that read the errors of its probes in shared +/// reports could learn which rows share the key's signs. +pub fn key_margin(error: f64) -> i8 { + if error.is_nan() { + return -3; + } + if error <= 0.0 { + return 3; + } + (KEY_TOLERANCE / error).log10().floor().clamp(-3.0, 3.0) as i8 +} + +/// Orders checks by how far they are over their tolerances. +fn score(check: &LogitsCheck) -> f64 { + (check.error / KEY_TOLERANCE).max(check.row_error / audit::TOLERANCE) +} + +/// Per row, [`KEY_VECTORS`] sign bits from `seed`. +fn signs(seed: &[u8; 32], rows: u64) -> Vec { + let mut hasher = blake3::Hasher::new_keyed(seed); + hasher.update(b"mesh-llm receipts head key v2"); + let mut bytes = vec![0u8; rows as usize * 2]; + hasher.finalize_xof().fill(&mut bytes); + bytes + .as_chunks::<2>() + .0 + .iter() + .map(|b| u16::from_le_bytes(*b)) + .collect() +} + +fn sign(signs: &[u16], row: u64, k: usize) -> f64 { + if signs[row as usize] >> k & 1 == 1 { + 1.0 + } else { + -1.0 + } +} + +fn encode_f64(values: &[f64]) -> String { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + crate::wire::encode_bytes(&bytes) +} + +fn decode_f64(text: &str) -> Result> { + let bytes = crate::wire::decode_bytes(text).context("decode a head key vector")?; + Ok(bytes + .as_chunks::<8>() + .0 + .iter() + .map(|c| f64::from_le_bytes(*c)) + .collect()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/head/key/tests.rs b/crates/skippy-receipts/src/head/key/tests.rs new file mode 100644 index 00000000..0057471f --- /dev/null +++ b/crates/skippy-receipts/src/head/key/tests.rs @@ -0,0 +1,423 @@ +use super::*; +use crate::weights::{MetaValue, test_gguf}; +use crate::wire::{RECEIPT_VERSION, StageCommitment, encode_f32}; + +const ROWS: u64 = 64; +const WIDTH: u64 = 8; + +fn model() -> WeightFile { + model_with(None) +} + +/// The toy model, dividing its logits by `logit_scale` when given. +fn model_with(logit_scale: Option) -> WeightFile { + let embd: Vec = (0..ROWS * WIDTH) + .map(|i| ((i * 37 % 101) as f32 - 50.0) / 25.0) + .collect(); + let mut meta = vec![ + ("general.architecture", MetaValue::Str("toy".into())), + ( + "toy.attention.layer_norm_rms_epsilon", + MetaValue::Float(1e-6), + ), + ]; + if let Some(scale) = logit_scale { + meta.push(("toy.logit_scale", MetaValue::Float(scale))); + } + test_gguf::open( + &meta, + &[ + ("output_norm.weight", vec![WIDTH], vec![1.0; WIDTH as usize]), + ("token_embd.weight", vec![WIDTH, ROWS], embd), + ], + ) +} + +fn residual() -> Vec { + (0..WIDTH).map(|i| i as f32 - 3.5).collect() +} + +/// A turn of two positions whose second token was sampled from the first. +fn receipt(sampled: i32) -> Receipt { + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 2, + tokens: vec![0, sampled], + generation_start: 1, + final_token: Some(1), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 1, + root: String::new(), + leaf_count: 0, + backend: "CPU".into(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: None, + } +} + +/// The honest logits at the residual, and their best token. +fn honest(weights: &WeightFile) -> (Vec, i32) { + let head = OutputHead::from_weights(weights).unwrap(); + let logits = head.logits(weights, &[residual()]).unwrap().remove(0); + let best = (0..logits.len()) + .max_by(|&a, &b| logits[a].total_cmp(&logits[b])) + .unwrap(); + (logits.iter().map(|&v| v as f32).collect(), best as i32) +} + +fn opening(logits: &[f32]) -> HeadOpening { + HeadOpening { + position: 0, + residual: encode_f32(&residual()), + path: Vec::new(), + logits: Some(encode_f32(logits)), + } +} + +fn check(weights: &WeightFile, key: &HeadKey, logits: &[f32], sampled: i32) -> HeadVerdict { + check_head_with_key( + weights, + key, + &receipt(sampled), + &[opening(logits)], + "CPU", + b"rows", + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap() +} + +#[test] +fn honest_logits_pass_the_key_check() { + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (logits, best) = honest(&weights); + let verdict = check(&weights, &key, &logits, best); + assert!(verdict.pass, "{verdict:?}"); + let checked = verdict.positions[0].logits.unwrap(); + assert!(checked.error < 1e-6, "{checked:?}"); +} + +#[test] +fn one_changed_logit_fails_the_key_check() { + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (mut logits, best) = honest(&weights); + // lower the honest best below another token, which the node then samples + let (other, _) = logits + .iter() + .enumerate() + .filter(|&(i, _)| i as i32 != best) + .max_by(|a, b| a.1.total_cmp(b.1)) + .unwrap(); + logits[best as usize] = logits[other] - 0.5; + let verdict = check(&weights, &key, &logits, other as i32); + assert!(!verdict.pass); + assert!(verdict.positions[0].logits.unwrap().error > KEY_TOLERANCE); +} + +#[test] +fn a_token_that_is_not_the_best_of_the_opened_logits_fails() { + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (logits, best) = honest(&weights); + let worst = (0..logits.len()) + .min_by(|&a, &b| logits[a].total_cmp(&logits[b])) + .unwrap(); + assert_ne!(worst as i32, best); + let verdict = check(&weights, &key, &logits, worst as i32); + assert!(!verdict.pass); + assert!(verdict.positions[0].logits.unwrap().pass); +} + +#[test] +fn a_key_survives_a_round_trip_and_fits_only_its_matrix() { + let weights = model(); + let key = HeadKey::build(&weights, [9; 32]).unwrap(); + let text = serde_json::to_string(&key).unwrap(); + let back: HeadKey = serde_json::from_str(&text).unwrap(); + assert_eq!(back, key); + assert!(back.fits(&weights)); + let other = test_gguf::open( + &[], + &[( + "token_embd.weight", + vec![WIDTH, ROWS + 1], + vec![0.0; ((ROWS + 1) * WIDTH) as usize], + )], + ); + assert!(!back.fits(&other)); +} + +#[test] +fn logits_divided_by_the_models_logit_scale_pass() { + let weights = model_with(Some(8.0)); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (logits, best) = honest(&weights); + let scaled: Vec = logits.iter().map(|v| v / 8.0).collect(); + let verdict = check(&weights, &key, &scaled, best); + assert!(verdict.pass, "{verdict:?}"); +} + +#[test] +fn scaled_logits_fail_when_the_model_has_no_scale() { + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (logits, best) = honest(&weights); + let scaled: Vec = logits.iter().map(|v| v / 8.0).collect(); + let verdict = check(&weights, &key, &scaled, best); + assert!(!verdict.pass, "{verdict:?}"); +} + +fn toy_key() -> Key { + Key { + signs: vec![0b0101, 0b0011, 0b1110], + vectors: vec![ + vec![1.0, -2.0, 0.5], + vec![0.25, 3.0, -1.0], + vec![-1.5, 0.75, 2.0], + vec![2.0, 1.0, 1.0], + ], + } +} + +#[test] +fn a_rounding_the_node_took_the_other_way_explains_the_key_residuals() { + let key = toy_key(); + let flips = vec![ + Flip { + changes: vec![(0, 0.01)], + }, + Flip { + changes: vec![(1, -0.02), (2, 0.004)], + }, + ]; + // the node's activation had the second flip + let residuals: Vec = key + .vectors + .iter() + .map(|v| v[1] * -0.02 + v[2] * 0.004) + .collect(); + let (taken, left) = explained(&key, &residuals, &flips); + assert_eq!(taken, vec![1]); + assert!(left < 1e-12); + // both of them + let both: Vec = key + .vectors + .iter() + .zip(&residuals) + .map(|(v, r)| r + v[0] * 0.01) + .collect(); + assert_eq!(explained(&key, &both, &flips).0, vec![0, 1]); +} + +#[test] +fn residuals_no_flip_explains_are_left_as_they_are() { + let key = toy_key(); + let flips = vec![Flip { + changes: vec![(0, 0.01)], + }]; + // a changed logit moves every residual by its sign, which no + // activation flip reproduces + let residuals = [0.3, -0.3, 0.3, 0.3]; + let (taken, left) = explained(&key, &residuals, &flips); + assert!(taken.len() <= 1); + assert!(left > 0.25, "{left}"); + // a residual that is not a number is left as the worst there is + let (_, left) = explained(&key, &[0.0, f64::NAN, 0.0, 0.0], &flips); + assert_eq!(left, f64::INFINITY); +} + +/// The node's fault that checking `opening` with a key finds. +fn fault(opening: HeadOpening) -> String { + use crate::node_fault::NodeFault; + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (_, best) = honest(&weights); + let error = check_head_with_key( + &weights, + &key, + &receipt(best), + &[opening], + "CPU", + b"rows", + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap_err(); + assert!( + NodeFault::find(&error).is_some(), + "not blamed on the node: {error:#}" + ); + format!("{error:#}") +} + +#[test] +fn logits_left_out_are_the_nodes_fault() { + // Without logits the client would read the whole output matrix and + // compute every logit, on every core: a node may not choose that. + let (logits, _) = honest(&model()); + let message = fault(HeadOpening { + logits: None, + ..opening(&logits) + }); + assert!(message.contains("opened no logits"), "{message}"); +} + +#[test] +fn logits_or_a_residual_that_do_not_fit_are_the_nodes_fault() { + let (logits, _) = honest(&model()); + let message = fault(opening(&logits[..logits.len() - 1])); + assert!(message.contains("63 logits for 64 tokens"), "{message}"); + for bad in [f32::NAN, f32::INFINITY] { + let mut changed = logits.clone(); + changed[5] = bad; + let message = fault(opening(&changed)); + assert!(message.contains("not a number"), "{message}"); + let mut residual = residual(); + residual[2] = bad; + let message = fault(HeadOpening { + residual: encode_f32(&residual), + ..opening(&logits) + }); + assert!(message.contains("not a number"), "{message}"); + } + let message = fault(HeadOpening { + residual: encode_f32(&residual()[..7]), + ..opening(&logits) + }); + assert!(message.contains("7 values"), "{message}"); + fault(HeadOpening { + logits: Some("not base64".into()), + ..opening(&logits) + }); +} + +#[test] +fn a_sampled_token_outside_the_vocabulary_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let (logits, _) = honest(&weights); + for token in [ROWS as i32, -1] { + let error = check_head_with_key( + &weights, + &key, + &receipt(token), + &[opening(&logits)], + "CPU", + b"rows", + (&TokenRule::Greedy, &Forcing::Free), + ) + .unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{token}: {error:#}"); + } +} + +#[test] +fn a_key_does_not_print_its_secrets() { + let key = HeadKey::build(&model(), [0xab; 32]).unwrap(); + let printed = format!("{key:?} {key:#?}"); + assert!(printed.contains("token_embd.weight"), "{printed}"); + assert!(!printed.contains("abab"), "{printed}"); + assert!(!printed.contains(&key.vectors[0]), "{printed}"); + assert!(!printed.contains("seed") && !printed.contains("vectors")); +} + +#[test] +fn a_key_that_parses_but_cannot_check_does_not_fit() { + // such a key would be kept and leave the head unchecked for good + let weights = model(); + let key = HeadKey::build(&weights, [9; 32]).unwrap(); + assert!(key.fits(&weights)); + let changed = |change: &dyn Fn(&mut serde_json::Value)| -> HeadKey { + let mut value = serde_json::to_value(&key).unwrap(); + change(&mut value); + serde_json::from_value(value).unwrap() + }; + let broken = [ + changed(&|key| key["seed"] = "not hex".into()), + changed(&|key| key["seed"] = "abcd".into()), + changed(&|key| { + key["vectors"].as_array_mut().unwrap().pop(); + }), + changed(&|key| key["vectors"][1] = "AAAAAAAAAAA=".into()), + changed(&|key| key["vectors"][2] = "@@".into()), + // a vector that holds a value that is not a number + changed(&|key| { + let mut vector = vec![1.0f64; WIDTH as usize]; + vector[3] = f64::NAN; + key["vectors"][0] = encode_f64(&vector).into(); + }), + ]; + for (i, key) in broken.iter().enumerate() { + assert!(!key.fits(&weights), "broken key {i} fits"); + } +} + +#[test] +fn two_changes_that_cancel_in_a_few_vectors_show_in_the_rest() { + // a node that lowers one logit and raises another by as much moves + // `r · y` by nothing in every vector where their signs agree: with 4 + // vectors one pair of rows in 16 agreed in all + let rows = 4096u64; + let signs = signs(&[9; 32], rows); + let first4 = |row: usize| signs[row] & 0xF; + let (a, b) = (1..rows as usize) + .find_map(|b| (first4(0) == first4(b)).then_some((0, b))) + .expect("a pair that agrees in the first 4 vectors"); + let key = Key { + signs, + vectors: vec![Vec::new(); KEY_VECTORS], + }; + let y = vec![0.5f32; rows as usize]; + let mut moved = y.clone(); + moved[a] -= 3.0; + moved[b] += 3.0; + let shifts: Vec = (0..KEY_VECTORS) + .map(|k| signed_sum(&key, k, &moved) - signed_sum(&key, k, &y)) + .collect(); + assert!(shifts[..4].iter().all(|s| s.abs() < 1e-9), "{shifts:?}"); + // 16 vectors miss such a pair 1 in 65,536 times; this one shows + assert!(shifts.iter().any(|s| s.abs() > 1.0), "{shifts:?}"); + // agreement in all 16 is as rare as that + let agreeing = (1..rows as usize) + .filter(|&row| key.signs[row] == key.signs[0]) + .count(); + assert!(agreeing <= 2, "{agreeing}"); +} + +#[test] +fn a_key_file_of_another_layout_does_not_parse() { + // the first layout had no version and 4 vectors: it is never read as + // a key of this one, and a client builds a new one + let weights = model(); + let key = HeadKey::build(&weights, [7; 32]).unwrap(); + let mut json = serde_json::to_value(&key).unwrap(); + assert_eq!(json["version"], KEY_VERSION); + assert_eq!(json["vectors"].as_array().unwrap().len(), KEY_VECTORS); + json.as_object_mut().unwrap().remove("version"); + assert!(serde_json::from_value::(json.clone()).is_err()); + json["version"] = 1.into(); + let old: HeadKey = serde_json::from_value(json).unwrap(); + assert!(!old.fits(&weights)); +} + +#[test] +fn a_report_shows_the_key_error_in_coarse_steps() { + assert_eq!(key_margin(KEY_TOLERANCE / 2.0), 0); + assert_eq!(key_margin(KEY_TOLERANCE / 20.0), 1); + assert_eq!(key_margin(KEY_TOLERANCE / 1e9), 3); + assert_eq!(key_margin(0.0), 3); + assert_eq!(key_margin(KEY_TOLERANCE * 2.0), -1); + assert_eq!(key_margin(f64::INFINITY), -3); + assert_eq!(key_margin(f64::NAN), -3); +} diff --git a/crates/skippy-receipts/src/head/opened_logits.rs b/crates/skippy-receipts/src/head/opened_logits.rs new file mode 100644 index 00000000..1283ff16 --- /dev/null +++ b/crates/skippy-receipts/src/head/opened_logits.rs @@ -0,0 +1,170 @@ +//! The logits a node opened at a head position, read for a check against +//! the claimed output matrix. +//! +//! Two checks read them: one with the client's secret head key +//! ([`super::key`]) and one over every row of the matrix, which needs no +//! secret ([`super::every_row`]). Both take the logits as the node sampled +//! from them, undo the scale and the bias a model applies after the +//! matrix, and compare a few drawn rows like any matmul. What they share +//! is here. + +use anyhow::Result; + +use super::OutputHead; +use crate::draw::DrawStream; +use crate::error_bound::all_finite; +use crate::node_fault::{BlameNode, ensure_node, node_fault}; +use crate::weights::{MetaValue, WeightFile}; +use crate::wire::HeadOpening; + +/// Random rows checked per position, besides the sampled token's. +pub(crate) const HEAD_ROWS: usize = 16; + +/// How far the scale the rows show may be from a candidate. +const SCALE_TOLERANCE: f64 = 1e-3; + +/// The check of one head position's opened logits against the claimed +/// output matrix. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LogitsCheck { + /// How far the logits are from the claimed head's, relative to their + /// norm, for the best profile. With a head key it is the largest + /// Freivalds difference over the key's vectors. Over every row it is + /// the norm of the difference of all of them. + pub error: f64, + /// The row check's error over the drawn rows and the sampled token's, + /// for the best profile. + pub row_error: f64, + pub profile: &'static str, + /// Roundings of the activation the node took the other way: values + /// within a few ulps of a rounding boundary + /// ([`crate::audit::rounding_flips`]). + pub rounding_flips: usize, + /// The check read every row of the output matrix, and no head key. + /// Anyone with the claimed GGUF repeats it. + pub every_row: bool, + pub pass: bool, +} + +/// One head position's logits and the activation the output matrix met. +pub(super) struct Opened { + /// The logits as the node opened them, one per token. + pub(super) logits: Vec, + /// The opened residual after the output norm. + pub(super) activation: Vec, +} + +/// Reads the logits and the residual of `opening` for a matrix of `rows` +/// rows. A position without logits is the node's fault: a node may not +/// leave them out to be judged on logits the client computes with other +/// rounding. So is a residual or a logit vector of the wrong length, or +/// one that holds a value that is not a number. +pub(super) fn read(head: &OutputHead, rows: u64, opening: &HeadOpening) -> Result { + let Some(logits) = opening.logit_values().or_node_fault()? else { + node_fault!("position {} opened no logits", opening.position); + }; + ensure_node!( + logits.len() as u64 == rows, + "position {} opened {} logits for {} tokens", + opening.position, + logits.len(), + rows + ); + ensure_node!( + all_finite(&logits), + "position {} opened a logit that is not a number", + opening.position + ); + let activation = head + .norm + .apply(&opening.residual_values().or_node_fault()?)?; + Ok(Opened { + logits, + activation: activation.iter().map(|&v| v as f32).collect(), + }) +} + +/// The uniform scale a model may apply to its logits after the matrix +/// (`logit_scale`), which leaves the greedy choice as it is. Some +/// architectures multiply by it and some divide, so a check accepts +/// either, or none, whichever the checked rows show. +pub(super) fn scale_candidates(weights: &WeightFile) -> Vec { + let scale = weights + .metadata + .iter() + .find(|(k, _)| k.ends_with(".logit_scale")) + .and_then(|(_, v)| match v { + MetaValue::Float(s) if *s > 0.0 => Some(*s), + _ => None, + }); + let mut out = vec![1.0]; + if let Some(s) = scale { + out.extend([s, 1.0 / s]); + } + out +} + +/// The candidate scale that the opened logits `y` show against the +/// reference logits of the checked rows. When none fits, 1: the logits are +/// then checked as they are, and the errors show how far off they are. +pub(super) fn shown_scale(reference: &[(usize, f64)], y: &[f32], scales: &[f64]) -> f64 { + let (dot, sq) = reference.iter().fold((0.0, 0.0), |(d, s), &(r, v)| { + (d + f64::from(y[r]) * v, s + v * v) + }); + if sq == 0.0 { + return 1.0; + } + let shown = dot / sq; + scales + .iter() + .copied() + .find(|&c| (shown / c - 1.0).abs() <= SCALE_TOLERANCE) + .unwrap_or(1.0) +} + +/// The logits the matrix alone gives: `y` without the scale and the bias. +pub(super) fn unbiased(head: &OutputHead, y: &[f32], scale: f64) -> Vec { + y.iter() + .enumerate() + .map(|(i, &v)| (f64::from(v) / scale - head.bias_of(i)) as f32) + .collect() +} + +/// The norm of `values`, and never 0, so an error relative to it is a +/// number. +pub(super) fn norm(values: &[f32]) -> f64 { + values + .iter() + .map(|&v| f64::from(v).powi(2)) + .sum::() + .sqrt() + .max(f64::MIN_POSITIVE) +} + +pub(super) fn dot(a: &[f64], b: &[f64]) -> f64 { + a.iter().zip(b).map(|(a, b)| a * b).sum() +} + +/// `count` distinct rows of `rows`, from the stream `domain` of `seed`. +pub(super) fn drawn_rows(seed: &[u8], domain: &str, count: usize, rows: u64) -> Vec { + let mut stream = DrawStream::new(seed, domain); + let mut picked = std::collections::BTreeSet::new(); + while picked.len() < count.min(usize::try_from(rows).unwrap_or(usize::MAX)) { + picked.insert(stream.below(rows)); + } + picked.into_iter().collect() +} + +/// [`HEAD_ROWS`] distinct rows of `rows`, from `seed`: the rows of the row +/// check. +pub(super) fn picked_rows(seed: &[u8], rows: u64) -> Vec { + drawn_rows(seed, "rows/output-head", HEAD_ROWS, rows) +} + +/// The rows of the row check at one position: the drawn ones and the +/// sampled token's. +pub(super) fn checked_rows(picked: &[u64], sampled: i32, rows: u64) -> Vec { + let mut checked = picked.to_vec(); + checked.extend(u64::try_from(sampled).ok().filter(|&s| s < rows)); + checked +} diff --git a/crates/skippy-receipts/src/head/reasoning_budget.rs b/crates/skippy-receipts/src/head/reasoning_budget.rs new file mode 100644 index 00000000..682f43dc --- /dev/null +++ b/crates/skippy-receipts/src/head/reasoning_budget.rs @@ -0,0 +1,503 @@ +//! Replays the reasoning-budget sampler of a turn, to know which of its +//! tokens the sampler forced. +//! +//! A thinking model gets a reasoning budget on ordinary requests. Its +//! sampler lets every token through until the model has reasoned for the +//! budget's tokens, then forces the tag that ends the reasoning, one token +//! at a time: it leaves the forced token as the only candidate. A forced +//! token is not the choice of the logits, so the head check must know +//! where the sampler forced one. Everywhere else the token is judged as in +//! a turn without a budget. +//! +//! The sampler's state follows from what it was built from and the tokens +//! the turn sampled, which the receipt names. The node states the first in +//! its sampler statement ([`BudgetStatement`]): the budget, the tag that +//! starts the reasoning, the tags that end it, and the text the chat +//! template placed after the prompt, which the sampler reads first. The +//! client turns those texts into tokens with the claimed model's own +//! tokenizer ([`Vocabulary`]) and runs the same state machine +//! ([`replay`]). +//! +//! The machine is a port of `common/reasoning-budget.cpp` of the pinned +//! llama.cpp, and of the prefill rule of `common_sampler_init` in +//! `common/sampling.cpp`. Skippy builds the sampler in +//! `src/skippy/sampling_config.cpp` and never ends the reasoning from +//! outside it. A change of those files needs the same change here. +//! +//! What stays open: the tags are the node's statement. The client does not +//! derive them from the chat template, so a node can state an end tag of +//! its own and have its tokens pass as forced. The statement bounds the +//! tags ([`MAX_TAG_BYTES`], [`MAX_END_TAGS`]), and a report shows them. + +use std::collections::BTreeMap; + +use anyhow::Result; + +use crate::turn; +use crate::wire::Receipt; + +/// The most bytes a stated start or end tag may hold. +pub const MAX_TAG_BYTES: usize = 256; +/// The most end tags a statement may name. +pub const MAX_END_TAGS: usize = 8; +/// The most bytes the stated prefill may hold: the text a chat template +/// places after the prompt for the model to continue. +pub const MAX_PREFILL_BYTES: usize = 1024; + +/// What a sampler statement says the node built the turn's reasoning-budget +/// sampler from. These are the node's words. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BudgetStatement { + /// The tokens of reasoning the sampler allows before it forces the end. + pub budget: i32, + /// The tag that starts the reasoning. + pub start: String, + /// The tags that end it. The sampler forces the first. + pub ends: Vec, + /// The text the chat template placed after the prompt. + pub prefill: String, +} + +impl BudgetStatement { + /// The sampler the statement `sampler` names: `Ok(None)` when it names + /// none, and the reason when what it names is outside the limits. + pub fn from_sampler(sampler: &str) -> Result, String> { + match turn::sampler_parameters(sampler) { + Some(parameters) => Self::from_parameters(¶meters), + None => Ok(None), + } + } + + /// Checks that the stated reasoning sampler, if any, has the types an + /// honest node writes: an object with a text start tag, a list of text + /// end tags and a text prefill or none. A statement past the limits is + /// not malformed; its tokens are left unjudged ([`Self::from_parameters`]). + pub(crate) fn check_types(p: &serde_json::Value) -> Result<(), String> { + let stated = &p[turn::REASONING]; + if stated.is_null() { + return Ok(()); + } + let texts = stated["ends"] + .as_array() + .is_some_and(|ends| ends.iter().all(serde_json::Value::is_string)); + let well_typed = stated.is_object() + && stated["start"].is_string() + && texts + && (stated["prefill"].is_null() || stated["prefill"].is_string()); + if well_typed { + Ok(()) + } else { + Err("the stated reasoning sampler is not a start tag, end tags and a prefill".into()) + } + } + + /// [`Self::from_sampler`] for the parameters of a statement. + pub(crate) fn from_parameters(p: &serde_json::Value) -> Result, String> { + let stated = &p[turn::REASONING]; + if stated.is_null() { + return Ok(None); + } + let Some(budget) = p["reasoning_budget"].as_i64().filter(|b| *b >= 0) else { + return Err("the statement names reasoning tags and no reasoning budget".into()); + }; + let text = |value: &serde_json::Value, what: &str, most: usize| { + let text = value + .as_str() + .ok_or_else(|| format!("the stated {what} is not text"))?; + if text.len() > most { + return Err(format!( + "the stated {what} holds {} bytes, more than {most}", + text.len() + )); + } + Ok(text.to_owned()) + }; + let start = text( + &stated["start"], + "start tag of the reasoning", + MAX_TAG_BYTES, + )?; + if start.is_empty() { + return Err( + "the statement names a reasoning budget sampler without a start tag".into(), + ); + } + let ends = stated["ends"] + .as_array() + .ok_or("the statement names no end tags of the reasoning")?; + if ends.is_empty() || ends.len() > MAX_END_TAGS { + return Err(format!( + "the statement names {} end tags of the reasoning; it may name 1 to {MAX_END_TAGS}", + ends.len() + )); + } + let ends = ends + .iter() + .map(|end| text(end, "end tag of the reasoning", MAX_TAG_BYTES)) + .collect::, _>>()?; + if ends.iter().any(String::is_empty) { + return Err("the statement names an empty end tag of the reasoning".into()); + } + let prefill = match &stated["prefill"] { + serde_json::Value::Null => String::new(), + value => text(value, "prefill", MAX_PREFILL_BYTES)?, + }; + Ok(Some(Self { + budget: i32::try_from(budget).unwrap_or(i32::MAX), + start, + ends, + prefill, + })) + } +} + +/// The claimed model's tokenizer, as the replay needs it. +pub trait Vocabulary { + /// The tokens of `text`, with special tokens parsed and none added, as + /// the runtime reads a tag. + fn tokenize(&self, text: &str) -> Result>; + /// The bytes of one token's text. A control token gives its name. + fn piece(&self, token: i32) -> Result>; +} + +/// What the reasoning budget of a turn forced, for the head check. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Forcing { + /// The statement names no reasoning-budget sampler: no token is forced. + Free, + /// The sampler was replayed. + Replayed(Replayed), + /// The sampler could not be replayed, for this reason, so the turn's + /// tokens are not judged. + Unjudged(String), +} + +/// A replayed reasoning-budget sampler. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Replayed { + /// What the node says the sampler was built from. + pub statement: BudgetStatement, + /// By position, the token the sampler forced on the token sampled + /// from it. + forced: BTreeMap, +} + +impl Replayed { + /// The token the sampler forced on the token sampled from `position`. + pub fn forced_at(&self, position: u32) -> Option { + self.forced.get(&position).copied() + } +} + +impl Forcing { + /// The token the sampler forced on the token sampled from `position`. + pub(crate) fn forced_at(&self, position: u32) -> Option { + match self { + Self::Replayed(replayed) => replayed.forced_at(position), + Self::Free | Self::Unjudged(_) => None, + } + } + + /// Why the turn's tokens are not judged, when the sampler could not be + /// replayed. + pub fn unjudged(&self) -> Option<&str> { + match self { + Self::Unjudged(reason) => Some(reason), + Self::Free | Self::Replayed(_) => None, + } + } +} + +#[cfg(test)] +impl Forcing { + /// A replayed sampler that forced these tokens, by position. + pub(crate) fn forced(forced: &[(u32, i32)]) -> Self { + Self::Replayed(Replayed { + statement: BudgetStatement { + budget: 0, + start: "".into(), + ends: vec!["".into()], + prefill: String::new(), + }, + forced: forced.iter().copied().collect(), + }) + } +} + +/// Replays the reasoning-budget sampler `receipt`'s statement names over +/// the tokens the turn sampled. Without a `vocabulary` a statement that +/// names a sampler leaves the tokens unjudged. A tokenizer that fails is +/// the client's own, and leaves them unjudged too. +pub fn replay(receipt: &Receipt, vocabulary: Option<&dyn Vocabulary>) -> Forcing { + let Some(binding) = receipt.binding.as_ref() else { + return Forcing::Free; + }; + let statement = match BudgetStatement::from_sampler(&binding.sampler) { + Ok(Some(statement)) => statement, + Ok(None) => return Forcing::Free, + Err(reason) => return Forcing::Unjudged(reason), + }; + let Some(vocabulary) = vocabulary else { + return Forcing::Unjudged( + "the check has no tokenizer to replay the reasoning budget with".into(), + ); + }; + match forced_tokens(&statement, receipt, vocabulary) { + Ok(forced) => Forcing::Replayed(Replayed { statement, forced }), + Err(error) => Forcing::Unjudged(format!( + "the claimed model's tokenizer cannot replay the reasoning budget: {error:#}" + )), + } +} + +/// By position, the tokens the sampler of `statement` forced in the turn +/// of `receipt`. +fn forced_tokens( + statement: &BudgetStatement, + receipt: &Receipt, + vocabulary: &dyn Vocabulary, +) -> Result> { + let start = vocabulary.tokenize(&statement.start)?; + let mut ends = Vec::with_capacity(statement.ends.len()); + for end in &statement.ends { + let tokens = vocabulary.tokenize(end)?; + if !tokens.is_empty() { + ends.push(tokens); + } + } + // the runtime builds no sampler from a tag that is no token + if start.is_empty() || ends.is_empty() { + return Ok(BTreeMap::new()); + } + let forced = ends[0].clone(); + let mut machine = Machine::new(vec![start], ends, forced, statement.budget); + let mut whole = |token: i32| Ok(ends_a_character(&vocabulary.piece(token)?)); + for token in prefill_tokens(&statement.prefill, vocabulary)? { + machine.accept(token, &mut whole)?; + } + let mut out = BTreeMap::new(); + // the first sampled token comes from the last position of the prompt + let mut position = receipt.generation_start.saturating_sub(1); + for token in receipt.sampled_tokens() { + if let Some(forced) = machine.forcing() { + out.insert(position, forced); + } + machine.accept(token, &mut whole)?; + position = position.saturating_add(1); + } + Ok(out) +} + +/// The tokens of the prefill the sampler reads before the turn's own: a +/// tokenizer may put a space before the first special token, which the +/// runtime leaves out when the text starts with none. +fn prefill_tokens(prefill: &str, vocabulary: &dyn Vocabulary) -> Result> { + let mut tokens = vocabulary.tokenize(prefill)?; + let starts_with_space = |bytes: &[u8]| bytes.first().is_some_and(|&byte| is_c_space(byte)); + if let Some(&first) = tokens.first() + && starts_with_space(&vocabulary.piece(first)?) + && !starts_with_space(prefill.as_bytes()) + { + tokens.remove(0); + } + Ok(tokens) +} + +/// `isspace` of the C locale. +fn is_c_space(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r') +} + +/// Whether text that ends with `piece` ends with a whole UTF-8 character. +/// The runtime reads a control token's piece as empty here, and the client +/// reads its name; both end a character, since a name is whole text. +fn ends_a_character(piece: &[u8]) -> bool { + if piece.is_empty() { + return true; + } + for offset in 1..=piece.len().min(4) { + let byte = piece[piece.len() - offset]; + if byte & 0xc0 != 0x80 { + let expected = match byte { + 0xf0.. => 4, + 0xe0.. => 3, + 0xc0.. => 2, + _ => 1, + }; + return offset >= expected; + } + } + false +} + +/// Finds the token sequences of a tag at the end of the tokens it is +/// given. +#[derive(Clone, Debug)] +struct Matcher { + sequences: Vec>, + recent: Vec, + longest: usize, +} + +impl Matcher { + fn new(sequences: Vec>) -> Self { + let mut kept: Vec> = Vec::new(); + for sequence in sequences { + if !sequence.is_empty() && !kept.contains(&sequence) { + kept.push(sequence); + } + } + let longest = kept.iter().map(Vec::len).max().unwrap_or(0); + Self { + sequences: kept, + recent: Vec::new(), + longest, + } + } + + /// Whether one of the sequences ends at `token`. A match forgets the + /// tokens before it. + fn advance(&mut self, token: i32) -> bool { + self.recent.push(token); + if self.recent.len() > self.longest { + self.recent.remove(0); + } + let matched = self + .sequences + .iter() + .any(|sequence| self.recent.ends_with(sequence)); + if matched { + self.recent.clear(); + } + matched + } + + fn reset(&mut self) { + self.recent.clear(); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + /// Waiting for the start tag. + Idle, + /// Counting the tokens of the reasoning down. + Counting, + /// The budget ran out inside a character: waiting for its end. + WaitingForCharacter, + /// Forcing the end tag, token by token. + Forcing, + /// The reasoning ended. A new start tag counts again. + Done, +} + +/// The state machine of the reasoning-budget sampler. +#[derive(Clone, Debug)] +struct Machine { + start: Matcher, + end: Matcher, + forced: Vec, + budget: i32, + remaining: i32, + state: State, + /// The next token of `forced` to force. + force_position: usize, + /// Whether the sampler forced a token since it began to force. Tokens + /// it reads without sampling them, as the prefill, set none. + forcing_started: bool, +} + +impl Machine { + fn new(start: Vec>, ends: Vec>, forced: Vec, budget: i32) -> Self { + Self { + start: Matcher::new(start), + end: Matcher::new(ends), + forced, + budget, + remaining: budget, + state: State::Idle, + force_position: 0, + forcing_started: false, + } + } + + /// The token the sampler forces on the next sampled token, if it + /// forces one. The runtime asks this before it samples each token. + fn forcing(&mut self) -> Option { + if self.state != State::Forcing { + return None; + } + let forced = self.forced.get(self.force_position).copied()?; + self.forcing_started = true; + Some(forced) + } + + fn begin_forcing(&mut self) { + self.state = State::Forcing; + self.force_position = 0; + self.forcing_started = false; + } + + /// The reasoning starts: count its tokens, or force its end at once + /// when the budget allows none. + fn begin_counting(&mut self) { + self.state = State::Counting; + self.remaining = self.budget; + if self.remaining <= 0 { + self.begin_forcing(); + } + } + + /// Reads one token: a prefill token, or one the turn sampled. `whole` + /// says whether a token's text ends a character. + fn accept(&mut self, token: i32, whole: &mut dyn FnMut(i32) -> Result) -> Result<()> { + match self.state { + State::Idle => { + if self.start.advance(token) { + self.begin_counting(); + } + } + State::Counting | State::WaitingForCharacter => { + if self.end.advance(token) { + self.state = State::Done; + return Ok(()); + } + if self.state == State::WaitingForCharacter { + if whole(token)? { + self.begin_forcing(); + self.end.reset(); + } + return Ok(()); + } + self.remaining -= 1; + if self.remaining <= 0 { + if whole(token)? { + self.begin_forcing(); + } else { + self.state = State::WaitingForCharacter; + } + self.end.reset(); + } + } + State::Forcing => { + let ended = self.end.advance(token); + self.force_position += 1; + // tokens the sampler only reads can end the reasoning + // early; tokens it forces must also reach the tag's end + if (!self.forcing_started && ended) || self.force_position >= self.forced.len() { + self.state = State::Done; + } + } + State::Done => { + if self.start.advance(token) { + self.end.reset(); + self.begin_counting(); + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/head/reasoning_budget/tests.rs b/crates/skippy-receipts/src/head/reasoning_budget/tests.rs new file mode 100644 index 00000000..c00c7778 --- /dev/null +++ b/crates/skippy-receipts/src/head/reasoning_budget/tests.rs @@ -0,0 +1,406 @@ +use anyhow::bail; +use serde_json::json; + +use super::*; +use crate::turn::TurnBinding; +use crate::wire::{RECEIPT_VERSION, StageCommitment}; + +const START: i32 = 10; +/// The end tag is two tokens. +const END: [i32; 2] = [20, 21]; +/// A second end tag of one token. +const OTHER_END: i32 = 30; +/// The first bytes of a three-byte character, and its last byte alone. +const HALF: i32 = 40; +const REST: i32 = 41; +/// A token whose text starts with a space. +const SPACED: i32 = 50; + +/// A toy tokenizer: a tag is its tokens, and a text of digits is one token +/// per word. +struct Toy; + +impl Vocabulary for Toy { + fn tokenize(&self, text: &str) -> Result> { + let mut tokens = Vec::new(); + for word in text.split_whitespace() { + match word { + "" => tokens.push(START), + "" => tokens.extend(END), + "<|end|>" => tokens.push(OTHER_END), + "" => {} + "" => bail!("no such tag"), + // a tokenizer that puts a space before its first token + "" => tokens.extend([SPACED, START]), + word => tokens.push(word.parse()?), + } + } + Ok(tokens) + } + + fn piece(&self, token: i32) -> Result> { + Ok(match token { + HALF => vec![0xe2, 0x82], + REST => vec![0xac], + SPACED => b" x".to_vec(), + 99 => bail!("no such token"), + _ => b"a".to_vec(), + }) + } +} + +/// The tokens the sampler forces over `sampled`, by index: one entry per +/// sampled token, `Some` where the sampler forced it. +fn forced(budget: i32, prefill: &[i32], sampled: &[i32]) -> Vec> { + let mut machine = Machine::new( + vec![vec![START]], + vec![END.to_vec(), vec![OTHER_END]], + END.to_vec(), + budget, + ); + let mut whole = |token: i32| Ok(ends_a_character(&Toy.piece(token)?)); + for &token in prefill { + machine.accept(token, &mut whole).unwrap(); + } + sampled + .iter() + .map(|&token| { + let forced = machine.forcing(); + machine.accept(token, &mut whole).unwrap(); + forced + }) + .collect() +} + +#[test] +fn the_sampler_counts_the_reasoning_and_then_forces_its_end() { + // the start tag, two tokens of reasoning, then the end tag by force + let turn = [1, START, 2, 3, END[0], END[1], 4, 5]; + assert_eq!( + forced(2, &[], &turn), + [ + None, + None, + None, + None, + Some(END[0]), + Some(END[1]), + None, + None + ] + ); + // nothing is forced before the start tag, however long the turn + assert!(forced(2, &[], &[1, 2, 3, 4, 5]).iter().all(Option::is_none)); + // a budget the reasoning does not use up forces nothing + let short = [START, 1, END[0], END[1], 2, 3, 4]; + assert!(forced(5, &[], &short).iter().all(Option::is_none)); + // the other end tag ends the reasoning as well + let other = [START, 1, OTHER_END, 2, 3, 4]; + assert!(forced(2, &[], &other).iter().all(Option::is_none)); +} + +#[test] +fn the_forced_tokens_are_due_whatever_the_node_sampled() { + // the replay says what the sampler forced, not what the node took: a + // node that sampled other tokens there is still owed the tag + let turn = [START, 1, 7, 8, 9]; + assert_eq!( + forced(1, &[], &turn), + [None, None, Some(END[0]), Some(END[1]), None] + ); +} + +#[test] +fn a_budget_of_no_tokens_forces_the_end_at_once() { + let turn = [START, END[0], END[1], 1, 2]; + assert_eq!( + forced(0, &[], &turn), + [None, Some(END[0]), Some(END[1]), None, None] + ); +} + +#[test] +fn a_second_start_tag_counts_again() { + let turn = [ + START, 1, END[0], END[1], // ended by the model, inside the budget + 2, START, 3, 4, 6, END[0], END[1], // ended by force + 5, + ]; + let mut expected = vec![None; turn.len()]; + expected[9] = Some(END[0]); + expected[10] = Some(END[1]); + assert_eq!(forced(3, &[], &turn), expected); + // the first token of a tag the model began counts against the budget: + // when it uses the budget up, the sampler forces the whole tag + assert_eq!( + forced(2, &[], &[START, 1, END[0], END[0], END[1], 2]), + [None, None, None, Some(END[0]), Some(END[1]), None] + ); + // and after a forced end + let turn = [START, 1, END[0], END[1], START, 2, END[0], END[1], 3]; + assert_eq!( + forced(1, &[], &turn), + [ + None, + None, + Some(END[0]), + Some(END[1]), + None, + None, + Some(END[0]), + Some(END[1]), + None + ] + ); +} + +#[test] +fn a_budget_that_runs_out_inside_a_character_waits_for_its_end() { + // the budget's last token is half of a character: the sampler lets + // tokens through until one ends a character, and forces after it. A + // token that only continues the character does not end one for the + // sampler, which reads each token's text alone. + let turn = [START, 1, HALF, REST, 5, END[0], END[1], 2]; + assert_eq!( + forced(2, &[], &turn), + [ + None, + None, + None, + None, + None, + Some(END[0]), + Some(END[1]), + None + ] + ); + // an end tag while it waits ends the reasoning with no force + let ended = [START, 1, HALF, OTHER_END, 2, 3]; + assert!(forced(2, &[], &ended).iter().all(Option::is_none)); + assert!(ends_a_character(b"")); + assert!(ends_a_character("a\u{20ac}".as_bytes())); + assert!(!ends_a_character(&[b'a', 0xe2, 0x82])); + assert!(!ends_a_character(&[0xf0, 0x9f, 0x98])); + assert!(!ends_a_character(&[0x80, 0x80, 0x80, 0x80, 0x80])); +} + +#[test] +fn a_prefill_that_opens_the_reasoning_starts_the_count() { + // the template already wrote the start tag: the turn's first tokens + // are reasoning + assert_eq!( + forced(2, &[1, START], &[2, 3, END[0], END[1], 4]), + [None, None, Some(END[0]), Some(END[1]), None] + ); + // a prefill that opens and closes it leaves nothing to force, also + // with no budget: the sampler reads the end tag, and forces none of it + let closed = [START, END[0], END[1]]; + assert!(forced(0, &closed, &[1, 2, 3]).iter().all(Option::is_none)); + assert!(forced(2, &closed, &[1, 2, 3]).iter().all(Option::is_none)); + // a prefill that opens it with no budget: the tag is forced first + assert_eq!( + forced(0, &[START], &[END[0], END[1], 1]), + [Some(END[0]), Some(END[1]), None] + ); +} + +fn statement(budget: i64, reasoning: serde_json::Value) -> String { + turn::sampled(&json!({ + "temperature": 0.7, + "reasoning_budget": budget, + "reasoning": reasoning, + })) +} + +fn tags() -> serde_json::Value { + json!({ "start": "", "ends": ["", "<|end|>"], "prefill": "1 " }) +} + +/// A turn whose prompt ends at position 4 and that sampled `sampled`. +fn receipt(sampler: &str, sampled: &[i32]) -> Receipt { + let (last, tokens) = sampled.split_last().expect("a sampled token"); + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 2, + position_end: 5 + tokens.len() as u32, + tokens: [&[0, 0, 0], tokens].concat(), + generation_start: 5, + final_token: Some(*last), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 1, + root: String::new(), + leaf_count: 0, + backend: "CPU".into(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: Some(TurnBinding { + client_key: String::new(), + parent: None, + runtime: String::new(), + sampler: sampler.to_owned(), + node_key: String::new(), + turn_root: String::new(), + signature: String::new(), + }), + } +} + +#[test] +fn a_replay_names_the_positions_the_sampler_forced() { + // the prefill opened the reasoning; the budget is two tokens + let turn = receipt(&statement(2, tags()), &[2, 3, END[0], END[1], 4]); + let forcing = replay(&turn, Some(&Toy)); + let Forcing::Replayed(replayed) = &forcing else { + panic!("{forcing:?}"); + }; + assert_eq!(replayed.statement.budget, 2); + assert_eq!(replayed.statement.ends, ["", "<|end|>"]); + // the token sampled from position 6 sits at position 7: the third + // sampled token, the first the sampler forced + let forced: Vec> = (4..9).map(|p| forcing.forced_at(p)).collect(); + assert_eq!(forced, [None, None, Some(END[0]), Some(END[1]), None]); + assert!(forcing.unjudged().is_none()); + // tokens that are not the turn's own are not the sampler's + assert_eq!(forcing.forced_at(3), None); +} + +#[test] +fn a_statement_without_a_sampler_forces_nothing() { + // greedy, no budget, or a budget and no tags: the runtime built none + let free = [ + turn::GREEDY.to_owned(), + turn::sampled(&json!({ "temperature": 0.7 })), + turn::sampled(&json!({ "reasoning_budget": 64, "reasoning": null })), + turn::sampled(&json!({ "reasoning_budget": 64 })), + ]; + for sampler in free { + let turn = receipt(&sampler, &[START, 1, 2, 3]); + assert_eq!(replay(&turn, Some(&Toy)), Forcing::Free, "{sampler}"); + assert_eq!(replay(&turn, None), Forcing::Free, "{sampler}"); + } + let mut unbound = receipt(turn::GREEDY, &[1]); + unbound.binding = None; + assert_eq!(replay(&unbound, Some(&Toy)), Forcing::Free); + // a tag that is no token builds no sampler in the runtime either + let no_tokens = json!({ "start": "", "ends": [""] }); + let turn = receipt(&statement(0, no_tokens), &[START, 1, 2]); + let forcing = replay(&turn, Some(&Toy)); + assert!(matches!(forcing, Forcing::Replayed(_)), "{forcing:?}"); + assert!((0..12).all(|p| forcing.forced_at(p).is_none())); +} + +#[test] +fn the_prefill_drops_a_space_its_tokenizer_put_first() { + // the tokenizer puts a spaced token before the tag, and the text + // starts with none: the runtime leaves the token out + let spaced = json!({ "start": "", "ends": [""], "prefill": "" }); + let turn = receipt(&statement(1, spaced), &[1, END[0], END[1], 2]); + let forcing = replay(&turn, Some(&Toy)); + let forced: Vec> = (4..8).map(|p| forcing.forced_at(p)).collect(); + assert_eq!(forced, [None, Some(END[0]), Some(END[1]), None]); + assert_eq!(prefill_tokens("", &Toy).unwrap(), [START]); + // a text that starts with a space keeps it + assert_eq!(prefill_tokens(" ", &Toy).unwrap(), [SPACED, START]); + assert!(prefill_tokens("", &Toy).unwrap().is_empty()); +} + +#[test] +fn a_sampler_the_check_cannot_replay_leaves_the_tokens_unjudged() { + let turn = receipt(&statement(2, tags()), &[2, 3, 4]); + // no tokenizer + let reason = replay(&turn, None); + assert!( + reason + .unjudged() + .is_some_and(|r| r.contains("no tokenizer")), + "{reason:?}" + ); + // a tokenizer that fails is the client's own + let broken = json!({ "start": "", "ends": [""] }); + let forcing = replay(&receipt(&statement(2, broken), &[2, 3]), Some(&Toy)); + assert!( + forcing + .unjudged() + .is_some_and(|r| r.contains("no such tag")), + "{forcing:?}" + ); + let unknown = receipt(&statement(1, tags()), &[99, 1, 2]); + // token 99 uses the budget up, and its text cannot be read + let forcing = replay(&unknown, Some(&Toy)); + assert!( + forcing + .unjudged() + .is_some_and(|r| r.contains("no such token")), + "{forcing:?}" + ); + assert_eq!(forcing.forced_at(5), None); +} + +#[test] +fn a_statement_outside_the_limits_is_refused() { + let long = "x".repeat(MAX_TAG_BYTES + 1); + let many: Vec<&str> = vec![""; MAX_END_TAGS + 1]; + let refused = [ + ( + json!({ "start": "", "ends": [""] }), + "without a start tag", + ), + ( + json!({ "ends": [""] }), + "start tag of the reasoning is not text", + ), + (json!({ "start": 7, "ends": [""] }), "is not text"), + ( + json!({ "start": long, "ends": [""] }), + "more than 256", + ), + (json!({ "start": "" }), "no end tags"), + (json!({ "start": "", "ends": [] }), "0 end tags"), + (json!({ "start": "", "ends": many }), "9 end tags"), + (json!({ "start": "", "ends": [""] }), "empty end tag"), + ( + json!({ "start": "", "ends": [long] }), + "more than 256", + ), + ( + json!({ "start": "", "ends": [["a"]] }), + "is not text", + ), + ( + json!({ "start": "", "ends": [""], "prefill": "y".repeat(MAX_PREFILL_BYTES + 1) }), + "more than 1024", + ), + (json!(""), "is not text"), + ]; + for (reasoning, why) in refused { + let sampler = statement(4, reasoning.clone()); + let error = BudgetStatement::from_sampler(&sampler).unwrap_err(); + assert!(error.contains(why), "{reasoning}: {error}"); + let forcing = replay(&receipt(&sampler, &[1, 2]), Some(&Toy)); + assert_eq!(forcing.unjudged(), Some(error.as_str())); + } + // tags without a budget name no sampler the runtime builds + for budget in [json!(null), json!(-1)] { + let sampler = turn::sampled(&json!({ "reasoning_budget": budget, "reasoning": tags() })); + let error = BudgetStatement::from_sampler(&sampler).unwrap_err(); + assert!(error.contains("no reasoning budget"), "{error}"); + } + // the limits themselves pass, and a budget past any turn is kept + let edge = json!({ + "start": "x".repeat(MAX_TAG_BYTES), + "ends": vec![""; MAX_END_TAGS], + "prefill": "y".repeat(MAX_PREFILL_BYTES), + }); + let stated = BudgetStatement::from_sampler(&statement(i64::MAX, edge)) + .unwrap() + .unwrap(); + assert_eq!(stated.budget, i32::MAX); + assert_eq!(stated.ends.len(), MAX_END_TAGS); +} diff --git a/crates/skippy-receipts/src/head/sampling.rs b/crates/skippy-receipts/src/head/sampling.rs new file mode 100644 index 00000000..54b598e1 --- /dev/null +++ b/crates/skippy-receipts/src/head/sampling.rs @@ -0,0 +1,627 @@ +//! What a turn's sampler statement lets the head check judge of its tokens. +//! +//! A greedy turn must take the best logit. A sampled turn draws from the +//! candidates its filters keep: the token must be one the stated filters +//! keep, judged on the checked logits, and when the statement names a draw +//! a client can replay ([`DrawRule`]) it must be the one that draw picks +//! ([`super::draw`]). That catches a node that writes tokens of its own +//! choosing. Penalties, a grammar and the other samplers depend on more +//! than the logits, so a turn that uses them gets no token judgement; its +//! logits are still checked. What leaves a turn's tokens or its draw +//! unjudged is a [`Gap`], and a client holds each one against its request +//! ([`crate::sampler_request`]): a node may not opt out of the judgement. +//! +//! The rule follows the runtime (`src/skippy/sampling_config.cpp`): an empty +//! chain is its default chain, a temperature of 0 keeps the best logit, a +//! top-p of 0 keeps the best token, and the model's suppressed tokens and, +//! for a turn that ignores its end, the end-of-generation tokens are taken +//! out of every candidate list before the chain runs ([`TokenRule::without`]). +//! +//! A reasoning budget forces the tag that ends the reasoning, and leaves +//! every other token to this rule. The head check replays which tokens it +//! forced ([`super::reasoning_budget`]). +//! +//! A statement whose fields do not have the types an honest node writes is +//! the node's fault ([`check_statement`]): the node signed it. + +use anyhow::Result; +use serde_json::Value; + +use super::draw::IndexedDraw; +use super::reasoning_budget::BudgetStatement; +use crate::node_fault::node_fault; +use crate::turn; + +/// How the head check judges the token a turn took at a position. +#[derive(Clone, Debug, PartialEq)] +pub enum TokenRule { + /// The best logit, within the tie band. + Greedy, + /// A token the filters keep, applied in order to the logits plus + /// `biases`, and the one the draw picks among them when it can be + /// replayed. + Filtered { + filters: Vec, + biases: Vec<(i32, f64)>, + draw: DrawRule, + }, + /// The sampler is beyond the check, for this reason. + Unjudged(String), +} + +/// Whether the check can replay which of the kept candidates a turn drew. +#[derive(Clone, Debug, PartialEq)] +pub enum DrawRule { + /// The statement names the indexed draw and its seed. + Indexed(IndexedDraw), + /// The chain keeps the best logit alone, so the turn draws nothing: + /// the kept-set rule is the whole judgement. + Single, + /// The draw is beyond the check, for this reason. + Unjudged(String), +} + +/// What a sampler statement leaves beyond the token judgement. Each is +/// something a client asks for; a node that states one its client did not +/// ask for contradicts the request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Gap { + /// A grammar constrains the tokens. + Grammar, + /// Mirostat replaces the sampler chain. + Mirostat, + /// A sampler the check does not replay is on: a penalty, DRY, + /// typical-p, top-n-sigma or XTC. + Sampler(String), + /// The temperature is dynamic. + DynamicTemperature, + /// The chain names a sampler the check does not know. + Unknown(String), + /// The turn draws from its chain and names no draw a client can + /// replay. + NoDraw, +} + +impl Gap { + pub fn describe(&self) -> String { + match self { + Self::Grammar => "a grammar constrains the tokens".into(), + Self::Mirostat => "mirostat replaces the sampler chain".into(), + Self::Sampler(name) => format!("the {name} sampler is on"), + Self::DynamicTemperature => "the temperature is dynamic".into(), + Self::Unknown(name) => format!("the {name} sampler is unknown"), + Self::NoDraw => "the node names no draw a client can replay".into(), + } + } +} + +/// A draw the check replays: the candidates are the tokens `filters` keep +/// of the logits plus `biases`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ReplayedDraw<'a> { + pub(crate) draw: IndexedDraw, + pub(crate) filters: &'a [Filter], + pub(crate) biases: &'a [(i32, f64)], +} + +/// One candidate filter of the sampler chain, in the stated order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Filter { + TopK(u32), + TopP(f64), + MinP(f64), + /// Divides the logits the later filters see. + Temperature(f64), +} + +/// The chain the runtime runs when a request names none of its own, as +/// `sampling_params` of `src/skippy/sampling_config.cpp` builds it from +/// the stated typical-p and top-p. +pub(crate) fn default_chain(typical_p: f64, top_p: f64) -> Vec<&'static str> { + let between = |p: f64| p > 0.0 && p < 1.0; + [ + "penalties", + "dry", + "top_n_sigma", + "top_k", + "typical_p", + "top_p", + "min_p", + "xtc", + "temperature", + ] + .into_iter() + .filter(|name| match *name { + "typical_p" => between(typical_p), + "top_p" => between(top_p), + _ => true, + }) + .collect() +} + +/// The samplers a chain may name that leave the candidates alone when +/// their parameters are neutral, with whether they are. `None` for a name +/// that is no such sampler; an error for a statement without the sampler's +/// parameters. +pub(crate) fn neutral(name: &str, p: &Value) -> Option> { + let f = |value: &Value, key: &str| { + value + .as_f64() + .ok_or_else(|| format!("the statement names the {name} sampler and no number {key}")) + }; + let neutral = || -> Result { + Ok(match name { + "penalties" => { + f(&p["repeat_penalty"], "repeat_penalty")? == 1.0 + && f(&p["frequency_penalty"], "frequency_penalty")? == 0.0 + && f(&p["presence_penalty"], "presence_penalty")? == 0.0 + } + "dry" => f(&p["dry"]["multiplier"], "dry.multiplier")? == 0.0, + "top_n_sigma" => f(&p["top_nsigma"], "top_nsigma")? <= 0.0, + "typical_p" | "typ_p" => f(&p["typical_p"], "typical_p")? >= 1.0, + _ => f(&p["xtc"]["probability"], "xtc.probability")? <= 0.0, + }) + }; + matches!( + name, + "penalties" | "dry" | "top_n_sigma" | "typical_p" | "typ_p" | "xtc" + ) + .then(neutral) +} + +/// A sampled statement read with the types an honest node writes. +struct Read { + filters: Vec, + biases: Vec<(i32, f64)>, + draw: DrawRule, + /// What leaves every token unjudged. + whole: Vec, + /// What leaves the draw unjudged. + draw_gaps: Vec, +} + +/// The number `p[key]`, which the statement must hold. +fn number(p: &Value, key: &str) -> Result { + p[key] + .as_f64() + .ok_or_else(|| format!("the sampler statement names no number {key}")) +} + +/// The number `p[key]`, or `default` when the statement leaves it out. +fn optional_number(p: &Value, key: &str, default: f64) -> Result { + match &p[key] { + Value::Null => Ok(default), + value => value + .as_f64() + .ok_or_else(|| format!("the stated {key} is not a number")), + } +} + +/// The chain's names: the stated chain, or the runtime's default one when +/// the statement names an empty chain, as the runtime reads it. +fn chain(p: &Value) -> Result, String> { + let samplers = p["samplers"] + .as_array() + .ok_or("the sampler statement names no sampler chain")?; + let names = samplers + .iter() + .map(|name| { + name.as_str() + .map(str::to_owned) + .ok_or_else(|| "the stated sampler chain holds a name that is not text".to_owned()) + }) + .collect::, _>>()?; + if !names.is_empty() { + return Ok(names); + } + let typical = optional_number(p, "typical_p", 1.0)?; + let top_p = number(p, "top_p")?; + Ok(default_chain(typical, top_p) + .into_iter() + .map(str::to_owned) + .collect()) +} + +/// The stated logit biases. +fn biases(p: &Value) -> Result, String> { + let malformed = || "the stated logit biases are not pairs of a token and a number".to_owned(); + match &p["logit_bias"] { + Value::Null => Ok(Vec::new()), + Value::Array(pairs) => pairs + .iter() + .map(|pair| { + let token = pair[0].as_i64().and_then(|t| i32::try_from(t).ok()); + match (token, pair[1].as_f64(), pair.as_array().map(Vec::len)) { + (Some(token), Some(bias), Some(2)) => Ok((token, bias)), + _ => Err(malformed()), + } + }) + .collect(), + _ => Err(malformed()), + } +} + +/// The types of the fields that do not shape the filters: what an honest +/// node writes, or nothing. +fn check_types(p: &Value) -> Result<(), String> { + let typed = |key: &str, fits: fn(&Value) -> bool, what: &str| { + if p[key].is_null() || fits(&p[key]) { + Ok(()) + } else { + Err(format!("the stated {key} is not {what}")) + } + }; + typed("draw", Value::is_string, "text")?; + typed("ignore_eos", Value::is_boolean, "true or false")?; + typed("grammar", Value::is_string, "text")?; + typed("reasoning_budget", Value::is_i64, "a whole number")?; + typed("mirostat", Value::is_object, "an object")?; + if !p["mirostat"]["mode"].is_null() && !p["mirostat"]["mode"].is_i64() { + return Err("the stated mirostat mode is not a whole number".into()); + } + let Some(seed) = p["seed"].as_u64() else { + return Err("the sampler statement names no seed".into()); + }; + u32::try_from(seed).map_err(|_| format!("the stated seed {seed} is past any seed"))?; + BudgetStatement::check_types(p) +} + +/// The stated filter of `name`, or `None` for a name that is no filter. +fn filter(p: &Value, name: &str) -> Result, String> { + Ok(Some(match name { + "top_k" => { + let k = p["top_k"] + .as_i64() + .ok_or("the stated top_k is not a whole number")?; + let k = i32::try_from(k).map_err(|_| format!("the stated top_k {k} is past any"))?; + // llama.cpp ignores a top-k of 0 or below + Filter::TopK(u32::try_from(k).unwrap_or(0)) + } + "top_p" => Filter::TopP(number(p, "top_p")?), + "min_p" => Filter::MinP(number(p, "min_p")?), + _ => return Ok(None), + })) +} + +/// The filters of a stated chain, in order, and what in it the check +/// cannot judge. +struct Chain { + filters: Vec, + gaps: Vec, + /// How many temperature samplers the chain holds. + temperatures: i32, +} + +/// The filter a temperature sampler of the chain is. llama.cpp's dynamic +/// temperature runs at any base temperature, 0 included +/// (`llama_sampler_temp_ext_apply`); a temperature of 0 that is not +/// dynamic keeps the best logit (`llama_sampler_temp_impl`). +fn temperature_filter(temperature: f64, dynamic: bool) -> Filter { + if dynamic { + Filter::Temperature(f64::NAN) + } else if temperature <= 0.0 { + Filter::TopK(1) + } else { + Filter::Temperature(temperature) + } +} + +/// Reads the stated chain of `p` at `temperature`. +fn read_chain(p: &Value, temperature: f64, dynamic: bool) -> Result { + let mut read = Chain { + filters: Vec::new(), + gaps: Vec::new(), + temperatures: 0, + }; + for name in chain(p)? { + if let Some(found) = filter(p, &name)? { + read.filters.push(found); + } else if matches!(name.as_str(), "temperature" | "temp") { + read.temperatures += 1; + read.filters.push(temperature_filter(temperature, dynamic)); + } else { + match neutral(&name, p) { + Some(Ok(true)) => {} + Some(Ok(false)) => read.gaps.push(Gap::Sampler(name)), + Some(Err(malformed)) => return Err(malformed), + None => read.gaps.push(Gap::Unknown(name)), + } + } + } + // a temperature after every filter changes only the draw + while matches!(read.filters.last(), Some(Filter::Temperature(_))) { + read.filters.pop(); + } + // a dynamic temperature before a filter changes what the filter keeps + if read + .filters + .iter() + .any(|f| matches!(f, Filter::Temperature(t) if t.is_nan())) + { + read.gaps.push(Gap::DynamicTemperature); + } + Ok(read) +} + +/// The draw a statement `p` of `chain` names, and what leaves it unjudged. +/// `whole` is what leaves every token unjudged already. +fn read_draw( + p: &Value, + chain: &Chain, + temperature: f64, + dynamic: bool, + whole: &[Gap], +) -> (DrawRule, Vec) { + // a temperature of 0 or a top-k of 1 leaves one candidate, which + // `common_sampler_init` takes without a draw when the chain ends in it + if chain.filters.contains(&Filter::TopK(1)) { + return (DrawRule::Single, Vec::new()); + } + if dynamic && chain.temperatures > 0 { + let gap = Gap::DynamicTemperature; + return (DrawRule::Unjudged(gap.describe()), vec![gap]); + } + if p["draw"].as_str() == Some(turn::INDEXED_DRAW) { + let seed = p["seed"].as_u64().and_then(|s| u32::try_from(s).ok()); + let draw = IndexedDraw { + seed: seed.unwrap_or_default(), + // every temperature of the chain divides the logits the draw sees + temperature: (0..chain.temperatures).fold(1.0, |product, _| product * temperature), + }; + return (DrawRule::Indexed(draw), Vec::new()); + } + // mirostat draws by itself: the whole turn is already unjudged + let gaps = if whole.is_empty() { + vec![Gap::NoDraw] + } else { + Vec::new() + }; + (DrawRule::Unjudged(Gap::NoDraw.describe()), gaps) +} + +/// Reads the parameters `p` of a sampled statement, or says how they are +/// malformed. +fn read(p: &Value) -> Result { + check_types(p)?; + let temperature = number(p, "temperature")?; + let dynamic = optional_number(p, "dynatemp_range", 0.0)? > 0.0; + let mut whole = Vec::new(); + if p["grammar"].as_str().is_some_and(|g| !g.is_empty()) { + whole.push(Gap::Grammar); + } + if p["mirostat"]["mode"].as_i64().unwrap_or(0) != 0 { + whole.push(Gap::Mirostat); + } + let chain = read_chain(p, temperature, dynamic)?; + whole.extend(chain.gaps.iter().cloned()); + let (draw, draw_gaps) = read_draw(p, &chain, temperature, dynamic, &whole); + Ok(Read { + filters: chain.filters, + biases: biases(p)?, + draw, + whole, + draw_gaps, + }) +} + +/// Checks that `sampler`, a receipt's sampler statement, is one an honest +/// node writes: [`turn::GREEDY`], or a sampled statement whose fields have +/// the types the node writes them with. A statement that is not is the +/// node's fault: it signed it. A statement that is well formed and states +/// something the check cannot judge is not ([`gaps`]). +pub fn check_statement(sampler: &str) -> Result<()> { + if sampler == turn::GREEDY { + return Ok(()); + } + let Some(parameters) = turn::sampler_parameters(sampler).filter(Value::is_object) else { + node_fault!("the sampler statement is neither greedy nor a list of parameters"); + }; + if let Err(malformed) = read(¶meters) { + node_fault!("the sampler statement is malformed: {malformed}"); + } + Ok(()) +} + +/// What the sampled statement `p` leaves beyond the token judgement, or +/// how it is malformed. +pub fn gaps(p: &Value) -> Result, String> { + let read = read(p)?; + Ok(read.whole.into_iter().chain(read.draw_gaps).collect()) +} + +/// Whether the statement `sampler` says the turn never picked an +/// end-of-generation token (`ignore_eos`). +pub fn ignores_end_tokens(sampler: &str) -> bool { + turn::sampler_parameters(sampler).is_some_and(|p| p["ignore_eos"].as_bool() == Some(true)) +} + +impl TokenRule { + /// The rule a receipt's sampler statement gives. + pub(crate) fn from_sampler(sampler: &str) -> Self { + if sampler == turn::GREEDY { + return Self::Greedy; + } + let Some(parameters) = turn::sampler_parameters(sampler) else { + return Self::Unjudged("the sampler statement names no parameters".into()); + }; + match read(¶meters) { + Ok(read) => match read.whole.first() { + Some(gap) => Self::Unjudged(gap.describe()), + None => Self::Filtered { + filters: read.filters, + biases: read.biases, + draw: read.draw, + }, + }, + Err(malformed) => Self::Unjudged(format!("the statement is malformed: {malformed}")), + } + } + + /// The rule in words, for a report. + pub fn describe(&self) -> String { + match self { + Self::Greedy => "the greedy choice".into(), + Self::Filtered { + filters, + biases, + draw, + } => { + let mut parts: Vec = filters + .iter() + .map(|f| match f { + Filter::TopK(k) => format!("top_k {k}"), + Filter::TopP(p) => format!("top_p {p}"), + Filter::MinP(p) => format!("min_p {p}"), + Filter::Temperature(t) => format!("temperature {t}"), + }) + .collect(); + if !biases.is_empty() { + parts.insert(0, format!("{} logit biases", biases.len())); + } + let kept = format!("kept by the sampler ({})", parts.join(", ")); + match draw { + DrawRule::Indexed(draw) => { + format!("{kept} and picked by the draw of seed {}", draw.seed) + } + DrawRule::Single => kept, + DrawRule::Unjudged(reason) => format!("{kept}; draw not replayed: {reason}"), + } + } + Self::Unjudged(reason) => format!("not judged: {reason}"), + } + } + + /// The rule for a turn whose runtime took `excluded` out of every + /// candidate list before its chain ran: the model's suppressed tokens, + /// and for a turn that ignores its end the end-of-generation tokens. + /// llama.cpp gives them a logit bias of minus infinity + /// (`common_sampler_init` in `common/sampling.cpp`, `chat_params` in + /// `src/skippy/sampling_config.cpp`). An error is why the client cannot + /// read which tokens those are: the token judgement is then the + /// client's gap, and no node's. + pub fn without(self, excluded: Result<&[i32], &str>) -> Self { + let excluded = match excluded { + Ok([]) => return self, + Ok(tokens) => tokens, + Err(reason) => { + return match self { + Self::Unjudged(_) => self, + _ => Self::Unjudged(reason.to_owned()), + }; + } + }; + let removed = excluded.iter().map(|&token| (token, f64::NEG_INFINITY)); + match self { + // the greedy choice among the tokens left + Self::Greedy => Self::Filtered { + filters: vec![Filter::TopK(1)], + biases: removed.collect(), + draw: DrawRule::Single, + }, + Self::Filtered { + filters, + mut biases, + draw, + } => { + biases.extend(removed); + Self::Filtered { + filters, + biases, + draw, + } + } + Self::Unjudged(_) => self, + } + } + + /// The draw the rule replays, and what it draws over. + pub(crate) fn replayed_draw(&self) -> Option> { + match self { + Self::Filtered { + filters, + biases, + draw: DrawRule::Indexed(draw), + } => Some(ReplayedDraw { + draw: *draw, + filters, + biases, + }), + _ => None, + } + } + + /// Whether `sampled` is a token the filters keep from `logits`, with + /// `band` of slack in logits for the node's rounding. + pub fn keeps( + filters: &[Filter], + biases: &[(i32, f64)], + logits: &[f64], + sampled: usize, + band: f64, + ) -> bool { + let mut logits = biased(logits, biases); + // a token the runtime took out has no weight in any draw + if logits[sampled] == f64::NEG_INFINITY && logits.iter().any(|l| l.is_finite()) { + return false; + } + let mut band = band; + for filter in filters { + let s = logits[sampled]; + let best_alone = || logits.iter().filter(|&&l| l > s + band).count() == 0; + let kept = match *filter { + Filter::TopK(0) => true, + Filter::TopK(k) => logits.iter().filter(|&&l| l > s + band).count() < k as usize, + Filter::TopP(p) if p >= 1.0 => true, + // llama.cpp's top-p keeps the best token whatever the p + Filter::TopP(p) if p <= 0.0 => best_alone(), + Filter::TopP(p) => mass_above(&logits, s + band) < p, + Filter::MinP(p) if p <= 0.0 => true, + // no token reaches p of the best: llama.cpp keeps the best + Filter::MinP(p) if p > 1.0 => best_alone(), + Filter::MinP(p) => { + let best = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max); + s >= best + p.ln() - band + } + Filter::Temperature(t) => { + for l in &mut logits { + *l /= t; + } + band /= t; + true + } + }; + if !kept { + return false; + } + } + true + } +} + +/// `logits` with the turn's logit biases added, one after the other in +/// f32, as llama.cpp's logit-bias sampler adds them +/// (`llama_sampler_logit_bias_apply`). +pub(crate) fn biased(logits: &[f64], biases: &[(i32, f64)]) -> Vec { + let mut logits = logits.to_vec(); + for &(token, bias) in biases { + if let Some(l) = usize::try_from(token).ok().and_then(|t| logits.get_mut(t)) { + *l = f64::from(*l as f32 + bias as f32); + } + } + logits +} + +/// The softmax mass of the logits above `threshold`, over every logit. A +/// filter before this one keeps fewer candidates, which raises the mass, +/// so this is the most lenient reading. +fn mass_above(logits: &[f64], threshold: f64) -> f64 { + let best = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let (above, total) = logits.iter().fold((0.0, 0.0), |(above, total), &l| { + let e = (l - best).exp(); + (above + if l > threshold { e } else { 0.0 }, total + e) + }); + above / total +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/head/sampling/tests.rs b/crates/skippy-receipts/src/head/sampling/tests.rs new file mode 100644 index 00000000..fe0627ae --- /dev/null +++ b/crates/skippy-receipts/src/head/sampling/tests.rs @@ -0,0 +1,416 @@ +use super::*; + +fn statement(overrides: serde_json::Value) -> String { + let mut p = serde_json::json!({ + "seed": 7, + "samplers": ["penalties", "dry", "top_n_sigma", "top_k", "typical_p", "top_p", "min_p", "xtc", "temperature"], + "temperature": 0.8, + "dynatemp_range": 0.0, + "top_k": 40, + "top_p": 0.9, + "min_p": 0.05, + "typical_p": 1.0, + "top_nsigma": -1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "repeat_penalty": 1.0, + "dry": { "multiplier": 0.0 }, + "xtc": { "probability": 0.0, "threshold": 0.1 }, + "mirostat": { "mode": 0 }, + "logit_bias": [], + "grammar": null, + }); + for (k, v) in overrides.as_object().unwrap() { + p[k] = v.clone(); + } + turn::sampled(&p) +} + +fn keeps(rule: &TokenRule, logits: &[f64], sampled: usize) -> bool { + let TokenRule::Filtered { + filters, biases, .. + } = rule + else { + panic!("not a filtered rule: {rule:?}"); + }; + TokenRule::keeps(filters, biases, logits, sampled, 1e-6) +} + +#[test] +fn the_default_chain_keeps_likely_tokens_and_drops_the_tail() { + let rule = TokenRule::from_sampler(&statement(serde_json::json!({}))); + // two likely tokens and a long unlikely tail + let mut logits = vec![-10.0; 100]; + logits[0] = 5.0; + logits[1] = 4.5; + assert!(keeps(&rule, &logits, 0)); + assert!(keeps(&rule, &logits, 1)); + assert!(!keeps(&rule, &logits, 50)); +} + +#[test] +fn top_k_counts_better_tokens() { + let rule = TokenRule::from_sampler(&statement( + serde_json::json!({"top_k": 2, "top_p": 1.0, "min_p": 0.0}), + )); + let logits = [3.0, 2.0, 1.0, 0.0]; + assert!(keeps(&rule, &logits, 1)); + assert!(!keeps(&rule, &logits, 2)); +} + +#[test] +fn a_bias_moves_a_token_into_the_candidates() { + let rule = TokenRule::from_sampler(&statement( + serde_json::json!({"top_k": 1, "logit_bias": [[2, 10.0]]}), + )); + let logits = [3.0, 2.0, 1.0]; + assert!(keeps(&rule, &logits, 2)); + assert!(!keeps(&rule, &logits, 0)); +} + +#[test] +fn a_zero_temperature_keeps_only_the_best() { + let rule = TokenRule::from_sampler(&statement( + serde_json::json!({"temperature": 0.0, "logit_bias": [[1, 0.5]]}), + )); + let logits = [3.0, 2.9, 1.0]; + assert!(keeps(&rule, &logits, 1)); + assert!(!keeps(&rule, &logits, 0)); +} + +#[test] +fn min_p_after_temperature_uses_the_scaled_logits() { + let samplers = serde_json::json!(["temperature", "min_p"]); + let rule = TokenRule::from_sampler(&statement( + serde_json::json!({"samplers": samplers, "temperature": 0.5, "min_p": 0.1}), + )); + // ln(0.1) = -2.3: unscaled, 2.0 below the best is kept; at half the + // temperature it is 4.0 below + let logits = [0.0, -2.0]; + assert!(!keeps(&rule, &logits, 1)); +} + +#[test] +fn penalties_grammar_and_unknown_samplers_are_not_judged() { + for overrides in [ + serde_json::json!({"repeat_penalty": 1.1}), + serde_json::json!({"grammar": "abc"}), + serde_json::json!({"mirostat": {"mode": 2}}), + serde_json::json!({"samplers": ["top_k", "mystery"]}), + // a reasoning budget whose sampler the statement names badly + serde_json::json!({"reasoning_budget": 128, "reasoning": {"start": ""}}), + serde_json::json!({"dynatemp_range": 0.5, "samplers": ["temperature", "top_p"]}), + ] { + let rule = TokenRule::from_sampler(&statement(overrides.clone())); + assert!( + matches!(rule, TokenRule::Unjudged(_)), + "{overrides}: {rule:?}" + ); + } + // a dynamic temperature at the end only shapes the draw + let rule = TokenRule::from_sampler(&statement(serde_json::json!({"dynatemp_range": 0.5}))); + assert!(matches!(rule, TokenRule::Filtered { .. }), "{rule:?}"); + assert_eq!(TokenRule::from_sampler(turn::GREEDY), TokenRule::Greedy); + // a reasoning budget forces only the end of the reasoning, which the + // head check replays: the rule holds, with or without a sampler + for overrides in [ + serde_json::json!({"reasoning_budget": 128}), + serde_json::json!({ + "reasoning_budget": 128, + "reasoning": {"start": "", "ends": [""], "prefill": ""}, + }), + ] { + let rule = TokenRule::from_sampler(&statement(overrides.clone())); + assert!( + matches!(rule, TokenRule::Filtered { .. }), + "{overrides}: {rule:?}" + ); + } +} + +fn draw_of(rule: &TokenRule) -> &DrawRule { + let TokenRule::Filtered { draw, .. } = rule else { + panic!("not a filtered rule: {rule:?}"); + }; + draw +} + +#[test] +fn a_statement_that_names_the_indexed_draw_has_it_replayed() { + let named = serde_json::json!({ "draw": turn::INDEXED_DRAW }); + let rule = TokenRule::from_sampler(&statement(named.clone())); + assert_eq!( + draw_of(&rule), + &DrawRule::Indexed(IndexedDraw { + seed: 7, + temperature: 0.8 + }) + ); + assert!(rule.replayed_draw().is_some()); + assert!(rule.describe().ends_with("picked by the draw of seed 7")); + // a statement without the rule, as an older node writes it + let rule = TokenRule::from_sampler(&statement(serde_json::json!({}))); + assert!(matches!(draw_of(&rule), DrawRule::Unjudged(_))); + assert!(rule.replayed_draw().is_none()); + assert!( + rule.describe().contains("draw not replayed"), + "{}", + rule.describe() + ); + // the kept-token rule holds either way + let mut logits = vec![-10.0; 100]; + logits[0] = 5.0; + assert!(keeps(&rule, &logits, 0)); + assert!(!keeps(&rule, &logits, 50)); +} + +#[test] +fn a_draw_the_check_cannot_follow_is_not_replayed() { + let with = |overrides: serde_json::Value| { + let mut all = serde_json::json!({ "draw": turn::INDEXED_DRAW }); + for (k, v) in overrides.as_object().unwrap() { + all[k] = v.clone(); + } + TokenRule::from_sampler(&statement(all)) + }; + for (overrides, reason) in [ + (serde_json::json!({ "dynatemp_range": 0.5 }), "dynamic"), + (serde_json::json!({ "draw": "another-rule" }), "no draw"), + ] { + let rule = with(overrides.clone()); + let DrawRule::Unjudged(why) = draw_of(&rule) else { + panic!("{overrides}: replayed"); + }; + assert!(why.contains(reason), "{overrides}: {why}"); + } + // a turn that ignores its end draws among the other tokens: the draw + // is replayed without them + let rule = with(serde_json::json!({ "ignore_eos": true })).without(Ok(&[3])); + assert!( + rule.replayed_draw() + .is_some_and(|r| r.biases == [(3, f64::NEG_INFINITY)]) + ); + // a turn that is not sampled from the chain has no draw to replay + assert!( + with(serde_json::json!({ "grammar": "abc" })) + .replayed_draw() + .is_none() + ); +} + +#[test] +fn the_draw_sees_every_temperature_of_the_chain() { + let chain = |samplers: serde_json::Value, temperature: f64| { + let rule = TokenRule::from_sampler(&statement(serde_json::json!({ + "draw": turn::INDEXED_DRAW, "samplers": samplers, "temperature": temperature, + }))); + rule.replayed_draw() + .map(|replayed| replayed.draw.temperature) + }; + let close = |a: Option, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-12); + assert!(close( + chain(serde_json::json!(["top_k", "temperature"]), 0.5), + 0.5 + )); + // a chain without the temperature sampler does not divide the logits + assert!(close( + chain(serde_json::json!(["top_k", "top_p"]), 0.5), + 1.0 + )); + // a temperature before a filter still scales what the draw sees + assert!(close( + chain(serde_json::json!(["temperature", "top_k"]), 0.5), + 0.5 + )); + // a temperature of 0 keeps the best logit alone: the turn draws nothing + assert_eq!( + chain(serde_json::json!(["top_k", "temperature"]), 0.0), + None + ); +} + +#[test] +fn a_turn_that_keeps_the_best_logit_alone_has_no_draw() { + // a greedy request with a reasoning budget states a sampled turn at a + // temperature of 0, and may name a draw its chain never runs + let rule = TokenRule::from_sampler(&statement(serde_json::json!({ + "temperature": 0.0, + "seed": 7, + "draw": turn::INDEXED_DRAW, + "reasoning_budget": 64, + }))); + assert_eq!(draw_of(&rule), &DrawRule::Single); + assert!(rule.replayed_draw().is_none()); + assert!(!rule.describe().contains("draw"), "{}", rule.describe()); + let logits = [3.0, 2.9, 1.0]; + assert!(keeps(&rule, &logits, 0)); + assert!(!keeps(&rule, &logits, 1)); +} + +#[test] +fn a_statement_with_the_wrong_types_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + // an honest node writes each field with its type; a node that writes + // another opts out of the token judgement, so it is held to it + for overrides in [ + serde_json::json!({ "reasoning": 1 }), + serde_json::json!({ "reasoning_budget": 8, "reasoning": {"start": ""} }), + serde_json::json!({ "seed": null }), + serde_json::json!({ "seed": 4_294_967_296u64 }), + serde_json::json!({ "top_k": 5_000_000_000u64 }), + serde_json::json!({ "top_k": "40" }), + serde_json::json!({ "top_p": null }), + serde_json::json!({ "temperature": "hot" }), + serde_json::json!({ "draw": 1 }), + serde_json::json!({ "ignore_eos": "yes" }), + serde_json::json!({ "logit_bias": [[1]] }), + serde_json::json!({ "samplers": "top_k" }), + serde_json::json!({ "samplers": ["top_k", 3] }), + serde_json::json!({ "repeat_penalty": null }), + serde_json::json!({ "mirostat": 2 }), + ] { + let statement = statement(overrides.clone()); + let error = check_statement(&statement).expect_err(&overrides.to_string()); + assert!(NodeFault::find(&error).is_some(), "{overrides}: {error:#}"); + let rule = TokenRule::from_sampler(&statement); + assert!(matches!(rule, TokenRule::Unjudged(_)), "{overrides}"); + } + for text in ["sampled", "sampled [1]", "anything"] { + assert!(check_statement(text).is_err(), "{text}"); + } + // a well-formed statement of something the check cannot judge is not + for overrides in [ + serde_json::json!({}), + serde_json::json!({ "grammar": "abc", "repeat_penalty": 1.1 }), + serde_json::json!({ "samplers": ["top_k", "mystery"] }), + serde_json::json!({ "top_p": 7.0 }), + serde_json::json!({ "reasoning_budget": 8, "reasoning": {"start": "", "ends": []} }), + ] { + assert!( + check_statement(&statement(overrides.clone())).is_ok(), + "{overrides}" + ); + } + assert!(check_statement(turn::GREEDY).is_ok()); +} + +#[test] +fn what_leaves_a_turn_unjudged_is_named_as_a_gap() { + let gaps_of = |overrides: serde_json::Value| { + let mut all = serde_json::json!({ "draw": turn::INDEXED_DRAW }); + for (k, v) in overrides.as_object().unwrap() { + all[k] = v.clone(); + } + let statement = statement(all); + gaps(&turn::sampler_parameters(&statement).unwrap()).unwrap() + }; + assert!(gaps_of(serde_json::json!({})).is_empty()); + assert_eq!( + gaps_of(serde_json::json!({ "grammar": "abc" })), + [Gap::Grammar] + ); + assert_eq!(gaps_of(serde_json::json!({ "draw": null })), [Gap::NoDraw]); + assert_eq!( + gaps_of(serde_json::json!({ "repeat_penalty": 1.1 })), + [Gap::Sampler("penalties".into())] + ); + assert_eq!( + gaps_of(serde_json::json!({ "dynatemp_range": 0.5 })), + [Gap::DynamicTemperature] + ); + assert_eq!( + gaps_of(serde_json::json!({ "samplers": ["mystery", "temperature"] })), + [Gap::Unknown("mystery".into())] + ); + // mirostat picks its token itself: no draw is missing + assert_eq!( + gaps_of(serde_json::json!({ "mirostat": {"mode": 2}, "draw": null })), + [Gap::Mirostat] + ); + // a turn at a temperature of 0 draws nothing + assert!(gaps_of(serde_json::json!({ "temperature": 0.0, "draw": null })).is_empty()); +} + +#[test] +fn an_empty_chain_is_the_runtimes_default_chain() { + // `sampling_params` of `src/skippy/sampling_config.cpp` runs its default + // chain when a request names none: the filters hold + let rule = TokenRule::from_sampler(&statement( + serde_json::json!({"samplers": [], "top_k": 2, "top_p": 1.0, "min_p": 0.0}), + )); + let logits = [3.0, 2.0, 1.0, 0.0]; + assert!(keeps(&rule, &logits, 1)); + assert!(!keeps(&rule, &logits, 2), "{rule:?}"); + // and the default chain leaves a top-p of 1 out + assert_eq!( + default_chain(1.0, 1.0), + [ + "penalties", + "dry", + "top_n_sigma", + "top_k", + "min_p", + "xtc", + "temperature" + ] + ); + assert!(default_chain(0.5, 0.9).contains(&"typical_p")); +} + +#[test] +fn filters_at_their_bounds_keep_what_llama_keeps() { + let logits = [3.0, 2.0, 1.0, 0.0]; + let rule = |overrides: serde_json::Value| TokenRule::from_sampler(&statement(overrides)); + // `llama_sampler_top_p_apply` keeps the best token at a top-p of 0 + let zero_p = rule(serde_json::json!({"top_p": 0.0, "top_k": 0, "min_p": 0.0})); + assert!(keeps(&zero_p, &logits, 0)); + assert!(!keeps(&zero_p, &logits, 1)); + // a top-p of 1 keeps every token + let all_p = rule(serde_json::json!({"top_p": 1.0, "top_k": 0, "min_p": 0.0})); + assert!(keeps(&all_p, &logits, 3)); + // min-p 0 keeps every token, min-p 1 the best and its equals + let no_min = rule(serde_json::json!({"top_p": 1.0, "top_k": 0, "min_p": 0.0})); + assert!(keeps(&no_min, &logits, 3)); + let full_min = rule(serde_json::json!({"top_p": 1.0, "top_k": 0, "min_p": 1.0})); + assert!(keeps(&full_min, &logits, 0)); + assert!(!keeps(&full_min, &logits, 1)); + // a top-k below 0 is off, and one above the vocabulary keeps every token + for k in [-5, 1000] { + let k_rule = rule(serde_json::json!({"top_p": 1.0, "top_k": k, "min_p": 0.0})); + assert!(keeps(&k_rule, &logits, 3), "{k}"); + } +} + +#[test] +fn a_dynamic_temperature_at_zero_still_samples() { + // `llama_sampler_temp_ext_apply` samples with a range above 0 at any + // base temperature; the chain does not keep the best logit alone + let rule = TokenRule::from_sampler(&statement(serde_json::json!({ + "temperature": 0.0, + "dynatemp_range": 0.5, + "logit_bias": [[1, 0.5]], + }))); + let logits = [3.0, 2.0, 1.0, 0.0]; + assert!(keeps(&rule, &logits, 1), "{rule:?}"); + assert!(matches!(draw_of(&rule), DrawRule::Unjudged(_))); +} + +#[test] +fn tokens_the_runtime_takes_out_are_never_kept() { + let logits = [3.0, 2.9, 1.0]; + // the best token is suppressed: the greedy choice is the next one + let greedy = TokenRule::Greedy.without(Ok(&[0])); + assert!(keeps(&greedy, &logits, 1), "{greedy:?}"); + assert!(!keeps(&greedy, &logits, 0)); + assert_eq!(TokenRule::Greedy.without(Ok(&[])), TokenRule::Greedy); + // a sampled rule loses them too, whatever bias the statement gives them + let sampled = TokenRule::from_sampler(&statement( + serde_json::json!({"top_k": 0, "top_p": 1.0, "min_p": 0.0, "logit_bias": [[0, 5.0]]}), + )) + .without(Ok(&[0])); + assert!(!keeps(&sampled, &logits, 0)); + assert!(keeps(&sampled, &logits, 2)); + // a client that cannot read them judges nothing + let unread = TokenRule::Greedy.without(Err("no vocabulary")); + assert_eq!(unread, TokenRule::Unjudged("no vocabulary".into())); +} diff --git a/crates/skippy-receipts/src/layer_tensors.rs b/crates/skippy-receipts/src/layer_tensors.rs new file mode 100644 index 00000000..3fabc165 --- /dev/null +++ b/crates/skippy-receipts/src/layer_tensors.rs @@ -0,0 +1,195 @@ +//! The per-layer tensors a stage reports for receipts, found by graph +//! structure (see `docs/design/RECEIPTS_GLUE.md`). +//! +//! Every tensor is keyed by layer, kind and index: its ordinal among the +//! layer's tensors of that kind, in graph order. The same builder gives the +//! same order for a serving ubatch, a replay and an auditor's glue +//! evaluation, so the index names the same value in all three. + +use crate::commitment::ValueDigest; + +/// ggml type id of f32 values. +pub const GGML_F32: i32 = 0; +/// ggml type id of i32 values. +pub const GGML_I32: i32 = 26; + +/// A reported per-layer tensor (`skippy_receipt_tensor_kind`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum TensorKind { + /// The residual stream entering the layer; at `layer_end`, the stage output. + Residual, + /// An input of a token-mixing op that the layer computes, such as q. + MixingInput, + /// A row written to the KV cache or recurrent state. While serving and + /// in a replay it is the row as stored, in the cache's type; in a glue + /// evaluation it is the f32 value the layer computed for it. + MixingStored, + /// The output of a token-mixing region, such as attention's output. + MixingOutput, + /// The f32 input of a weight matmul. + MatmulInput, + MatmulOutput, + /// The experts a `mul_mat_id` used, i32. + ExpertIds, + /// The ids an `argsort` or top-k picked from scores, i32. + Selection, + /// The scores a selection picked from. + SelectionScores, + /// A final stage's logits at its output rows, reported with + /// `layer_end` by a replay of its last layer. + Logits, + /// The state a recurrent token-mixing op reads before the ubatch: a + /// column per sequence, at the sequence's first token of the ubatch. + MixingState, + /// A region evaluation's state the op leaves after its tokens. + MixingStateOut, +} + +/// The kinds the token-mixing leaf commits to, in leaf order. +pub(crate) const MIXING_KINDS: [TensorKind; 4] = [ + TensorKind::MixingInput, + TensorKind::MixingStored, + TensorKind::MixingOutput, + TensorKind::MixingState, +]; + +impl TensorKind { + pub fn from_code(code: i32) -> Option { + Some(match code { + 0 => Self::Residual, + 1 => Self::MixingInput, + 2 => Self::MixingStored, + 3 => Self::MixingOutput, + 4 => Self::MatmulInput, + 5 => Self::MatmulOutput, + 6 => Self::ExpertIds, + 7 => Self::Selection, + 8 => Self::SelectionScores, + 9 => Self::Logits, + 10 => Self::MixingState, + 11 => Self::MixingStateOut, + _ => return None, + }) + } + + pub fn code(self) -> i32 { + match self { + Self::Residual => 0, + Self::MixingInput => 1, + Self::MixingStored => 2, + Self::MixingOutput => 3, + Self::MatmulInput => 4, + Self::MatmulOutput => 5, + Self::ExpertIds => 6, + Self::Selection => 7, + Self::SelectionScores => 8, + Self::Logits => 9, + Self::MixingState => 10, + Self::MixingStateOut => 11, + } + } + + pub fn name(self) -> &'static str { + match self { + Self::Residual => "residual", + Self::MixingInput => "mixing input", + Self::MixingStored => "stored row", + Self::MixingOutput => "mixing output", + Self::MatmulInput => "matmul input", + Self::MatmulOutput => "matmul output", + Self::ExpertIds => "expert ids", + Self::Selection => "selection", + Self::SelectionScores => "selection scores", + Self::Logits => "logits", + Self::MixingState => "mixing state", + Self::MixingStateOut => "mixing state out", + } + } +} + +/// `skippy_receipt_tensor_flags`: the matmul is a router, whose output +/// feeds a selection. +pub(crate) const FLAG_ROUTER: i32 = 1; + +/// One column of a reported tensor. +#[derive(Clone, Copy, Debug)] +pub struct TensorColumn<'a> { + /// ggml type of the bytes: f32, i32, or a stored row's cache type. + pub ggml_type: i32, + pub flags: i32, + /// The weight's name for a matmul, else the graph node's name. + pub name: &'a str, + /// Little-endian values; empty when the recorder reported only the digest. + pub bytes: &'a [u8], + /// The digest of the values, when the recorder computed it where the + /// values are instead of copying them. + pub digest: Option, +} + +impl TensorColumn<'_> { + /// The digest a leaf binds the values by. + pub(crate) fn value_digest(&self) -> ValueDigest { + self.digest.unwrap_or_else(|| ValueDigest::of(self.bytes)) + } + + pub fn f32_values(&self) -> Option> { + (self.ggml_type == GGML_F32).then(|| decode_f32_bytes(self.bytes)) + } + + pub(crate) fn i32_values(&self) -> Option> { + (self.ggml_type == GGML_I32).then(|| { + self.bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| i32::from_le_bytes(*c)) + .collect() + }) + } +} + +/// The reported tensors of a ubatch, by column. +pub trait UbatchColumns: Sync { + /// Tensors of `kind` the ubatch reported for `layer`. + fn count(&self, layer: u32, kind: TensorKind) -> u32; + /// Column `col` of a tensor; `None` when the tensor holds no row for the + /// column (the final layer of a final stage keeps only output rows) or + /// was not reported. + fn column( + &self, + layer: u32, + kind: TensorKind, + index: u32, + col: usize, + ) -> Option>; +} + +pub fn decode_f32_bytes(bytes: &[u8]) -> Vec { + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect() +} + +pub fn f32_bytes(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +pub fn i32_bytes(values: &[i32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kind_codes_round_trip() { + for code in 0..12 { + assert_eq!(TensorKind::from_code(code).unwrap().code(), code); + } + assert!(TensorKind::from_code(12).is_none()); + } +} diff --git a/crates/skippy-receipts/src/lib.rs b/crates/skippy-receipts/src/lib.rs new file mode 100644 index 00000000..5c55ef0f --- /dev/null +++ b/crates/skippy-receipts/src/lib.rs @@ -0,0 +1,113 @@ +//! Verifiable inference receipts. +//! +//! A node that serves with receipts commits, per stage and per turn, to the +//! residual stream entering every layer and to each layer's token-mixing +//! values (attention's inputs, stored KV rows and output), with a Merkle root +//! over those leaves. It keeps a small replay log instead of the values. +//! The residual entering layer 0 binds each position's token. After the +//! turn, a client challenges a few layers at a few positions each. The node +//! replays the turn, opens those leaves, and adds the layers' weight matmuls +//! and selections, the input of layer 0, and the leaves at stage +//! boundaries. The client checks the receipt against the model and request +//! and the leaves against the roots ([`binding`]), the matmuls against rows +//! of the claimed GGUF's weights ([`audit`]), and the glue between them by +//! computing each layer and the input of layer 0 itself on the opened values +//! ([`glue`]; see `docs/design/RECEIPTS.md` and `RECEIPTS_GLUE.md`), +//! and the sampled tokens against the output head on the final residual +//! ([`head`]). +//! +//! An opening is a node's free text until it is checked. So the client +//! first holds it to the one form an answer has and to its Merkle roots +//! ([`binding`]), then every value in it to the claimed model's shapes +//! ([`opened_values`]), and only then compares anything. A check that stops +//! says whose fault that is ([`node_fault`]): a defect of what the node +//! sent fails the audit, and a check the client could not run says nothing +//! about the node. +//! +//! # Layers +//! +//! The crate has three layers. Each module below is in one of them. +//! +//! - **Shared.** The format of a receipt and the arithmetic that both +//! sides must do the same way. A shared module uses only shared modules. +//! [`wire`], [`commitment`], [`turn`], [`vrf`], `draw`, [`challenge`] +//! and [`layer_tensors`] are the format. [`attention`] is the layout of +//! a layer's attention and the partial of a block of it. `ggml_types`, +//! `dequant`, [`cache_types`] and [`activation_rounding`] decode and +//! round values, and [`rounding_profiles`] says which roundings a backend +//! may use for a weight type. [`node_fault`] marks an error that a defective value +//! causes. The shared decoders set the mark, and only a client reads it. +//! - **Node.** [`recorder`] records the leaves of each ubatch, commits a +//! turn and opens a challenge by replay. It uses shared modules only. +//! - **Client.** The checks of an opening, and the reader of the claimed +//! GGUF: [`binding`], [`opened_values`], [`audit`], [`glue`], [`head`], +//! [`attention_check`], [`recurrent`], [`coverage`], [`evidence`], +//! [`sampler_request`], `error_bound`, [`weights`], [`shards`], +//! [`sparse_copy`] and [`claimed_reads`]. A client module uses shared and +//! client modules. It never uses [`recorder`]. +//! +//! `draw`, `ggml_types`, `dequant` and `error_bound` are private to the +//! crate. No other crate uses them. +//! +//! `toy_turn`, behind the `test-support` feature, and the crate's own +//! tests use all three layers. +//! +//! `skippy-serving` uses the shared and node layers. The auditor in +//! `skippy-receipt-audit` and the Mesh host use the shared and client layers. +//! +//! `tests/layers.rs` reads the `// Layer:` comments below and every file +//! under `src/`. It fails when a module names a module of a layer that it +//! may not use. To add a module, put its `mod` line under the comment of +//! its layer. + +// Layer: shared +// +// The format of a receipt, and the arithmetic that a node and a client +// must do the same way. Uses shared modules only. +pub mod activation_rounding; +pub mod attention; +pub mod cache_types; +pub mod challenge; +pub mod commitment; +pub(crate) mod dequant; +pub(crate) mod draw; +pub(crate) mod ggml_types; +pub mod layer_tensors; +pub mod node_fault; +pub mod rounding_profiles; +pub mod turn; +pub mod vrf; +pub mod wire; + +// Layer: node +// +// What a serving stage runs: record, commit, open by replay. Uses shared +// modules only. +pub mod recorder; + +// Layer: client +// +// What an auditor runs: the checks of an opening against the receipt and +// the claimed GGUF. Uses shared and client modules, never `recorder`. +pub mod attention_check; +pub mod audit; +pub mod binding; +pub mod claimed_reads; +pub mod coverage; +pub(crate) mod error_bound; +pub mod evidence; +pub mod glue; +pub mod head; +pub mod opened_values; +pub mod recurrent; +pub mod sampler_request; +pub mod shards; +pub mod sparse_copy; +pub mod weights; + +// Layer: test support +// +// A toy model and one honest turn of it, for the tests of this crate and +// of the crates that audit receipts. Uses every layer. +#[cfg(any(test, feature = "test-support"))] +pub mod toy_turn; diff --git a/crates/skippy-receipts/src/node_fault.rs b/crates/skippy-receipts/src/node_fault.rs new file mode 100644 index 00000000..5cb3d147 --- /dev/null +++ b/crates/skippy-receipts/src/node_fault.rs @@ -0,0 +1,145 @@ +//! Who an audit error blames. +//! +//! A check of an opening can stop for two reasons that a client must not +//! mix up. Either the node's answer is defective: a value is missing, +//! malformed, of the wrong length, not a number, or not the one the receipt +//! commits to. That is the node's fault, and when the node signed the +//! answer, anyone can see it. Or the client could not run the check: the +//! claimed GGUF is out of reach, a weight read failed, its own evaluator +//! cannot load the layer. That says nothing about the node. +//! +//! An error is marked as the node's where it is created ([`NodeFault`]). +//! An error without the mark is the client's. So a new error source is +//! "could not run here" until someone decides otherwise, and a node cannot +//! turn a failure into no audit by provoking an error the code did not +//! foresee as its own. +//! +//! The mark is in the shared layer because the shared decoders of opened +//! values set it ([`crate::cache_types`], [`crate::attention`]). Only a +//! client reads it. A node that runs the same decoders on its own rows gets +//! an ordinary error. + +use std::fmt; + +use anyhow::Result; + +/// An error the serving node caused with what it sent. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NodeFault { + reason: String, +} + +impl NodeFault { + /// An error that blames the node, for `reason`. + pub fn error(reason: impl Into) -> anyhow::Error { + anyhow::Error::new(Self { + reason: reason.into(), + }) + } + + /// `error`, blamed on the node. An error that already blames it is + /// returned as it is. + pub fn blame(error: anyhow::Error) -> anyhow::Error { + if Self::find(&error).is_some() { + return error; + } + Self::error(format!("{error:#}")) + } + + /// The mark of `error`, when it blames the node. + pub fn find(error: &anyhow::Error) -> Option<&Self> { + error.downcast_ref::() + } + + pub fn reason(&self) -> &str { + &self.reason + } +} + +impl fmt::Display for NodeFault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.reason) + } +} + +impl std::error::Error for NodeFault {} + +/// Blames the node for the error of a result. +pub(crate) trait BlameNode { + /// The result with its error marked as the node's fault. + fn or_node_fault(self) -> Result; +} + +impl BlameNode for Result { + fn or_node_fault(self) -> Result { + self.map_err(NodeFault::blame) + } +} + +/// Fails with an error that blames the node, unless `condition` holds. +macro_rules! ensure_node { + ($condition:expr, $($reason:tt)+) => { + if !$condition { + return Err($crate::node_fault::NodeFault::error(format!($($reason)+))); + } + }; +} +pub(crate) use ensure_node; + +/// Fails with an error that blames the node. +macro_rules! node_fault { + ($($reason:tt)+) => { + return Err($crate::node_fault::NodeFault::error(format!($($reason)+))) + }; +} +pub(crate) use node_fault; + +#[cfg(test)] +mod tests { + use anyhow::Context; + + use super::*; + + fn defective() -> Result<()> { + ensure_node!(1 + 1 == 3, "position {}: the residual is short", 4); + Ok(()) + } + + #[test] + fn a_marked_error_blames_the_node_through_added_context() { + let error = defective().context("layer 3").unwrap_err(); + let fault = NodeFault::find(&error).expect("the node's fault"); + assert_eq!(fault.reason(), "position 4: the residual is short"); + assert_eq!( + format!("{error:#}"), + "layer 3: position 4: the residual is short" + ); + } + + #[test] + fn an_unmarked_error_blames_nobody() { + let error = anyhow::anyhow!("read past the end").context("fetch a weight row"); + assert!(NodeFault::find(&error).is_none()); + // blaming it keeps the whole message + let blamed = NodeFault::blame(error); + assert_eq!( + NodeFault::find(&blamed).unwrap().reason(), + "fetch a weight row: read past the end" + ); + // and blaming twice changes nothing + let again = NodeFault::blame(blamed); + assert_eq!( + format!("{again:#}"), + "fetch a weight row: read past the end" + ); + } + + #[test] + fn a_result_is_blamed_in_one_call() { + let decoded: Result = Err(anyhow::anyhow!("not base64")); + let error = decoded.or_node_fault().unwrap_err(); + assert!(NodeFault::find(&error).is_some()); + let fine: Result = Ok(1); + assert_eq!(fine.or_node_fault().unwrap(), 1); + } +} diff --git a/crates/skippy-receipts/src/opened_values.rs b/crates/skippy-receipts/src/opened_values.rs new file mode 100644 index 00000000..0196d0f7 --- /dev/null +++ b/crates/skippy-receipts/src/opened_values.rs @@ -0,0 +1,272 @@ +//! Every opened value against the shapes of the claimed model, before any +//! check reads it. +//! +//! An opening is a node's free text until it is checked. A value that is +//! not a number passes a comparison written with `>`; a column of the wrong +//! length stops a check with an error instead of a verdict; an id out of +//! range indexes past a tensor. So nothing is compared, read from the +//! claimed GGUF or given to the native evaluator before this has passed: +//! +//! - every f32 array is whole and holds only numbers: residuals, matmul +//! inputs and outputs, mixing values, logits and attention partials; +//! - a residual has the model's width, a matmul's input and output fit its +//! weight's columns and rows, and logits count the vocabulary; +//! - a matmul names a tensor of the claimed GGUF, and an expert or selected +//! id is one its weights hold; +//! - a stored row is of a type the auditor checks, in whole blocks. +//! +//! The shapes come from the GGUF's header alone, so this reads no weights +//! and needs no evaluator. Every failure is the node's fault +//! ([`crate::node_fault::NodeFault`]). What is left to fail afterwards is +//! the client's own: a weight read, a layer that does not load. + +use std::ops::Deref; + +use anyhow::{Context, Result, bail}; + +use crate::audit::check_matmul_shape; +use crate::binding::VerifiedOpening; +use crate::claimed_reads::TOKEN_EMBEDDING; +use crate::error_bound::all_finite; +use crate::head::head_weight; +use crate::node_fault::{BlameNode, ensure_node, node_fault}; +use crate::weights::{MetaValue, WeightFile}; +use crate::wire::{ + AnchorOpening, HeadOpening, LeafOpening, MatrixOpening, MixingKind, Receipt, StageOpening, + TensorOpening, +}; + +/// The shapes of the claimed model an opening must fit, from its GGUF's +/// header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ModelShapes { + /// Values of the residual stream at one position. + pub hidden: usize, + /// Logits the output head gives: one per token. + pub vocabulary: u64, + /// Tokens the model embeds, when it has a token embedding. + pub tokens: Option, +} + +impl ModelShapes { + /// Fails when the header does not name them, which says nothing about + /// a node. + pub fn of(weights: &WeightFile) -> Result { + let architecture = weights.metadata_str("general.architecture")?; + let key = format!("{architecture}.embedding_length"); + let hidden = match weights.metadata.get(&key) { + Some(MetaValue::Int(hidden)) if *hidden > 0 => usize::try_from(*hidden)?, + _ => bail!("the claimed GGUF names no {key}"), + }; + Ok(Self { + hidden, + vocabulary: weights.tensor(head_weight(weights))?.rows(), + tokens: weights.tensors.get(TOKEN_EMBEDDING).map(|t| t.rows()), + }) + } +} + +/// Checks that every token a receipt names is one the claimed model +/// embeds. A receipt is signed, so a token that is not is the node's fault. +pub fn check_tokens(receipt: &Receipt, shapes: &ModelShapes) -> Result<()> { + let Some(tokens) = shapes.tokens else { + return Ok(()); + }; + let held = |token: i32| u64::try_from(token).is_ok_and(|t| t < tokens); + if let Some(token) = receipt + .tokens + .iter() + .chain(&receipt.final_token) + .find(|&&token| !held(token)) + { + node_fault!("the receipt names token {token}; the claimed model embeds {tokens}"); + } + Ok(()) +} + +/// A verified opening whose every value fits the claimed model +/// ([`validate`]). The checks of an audit take this. +#[derive(Clone, Copy, Debug)] +pub struct ValidatedOpening<'a>(VerifiedOpening<'a>); + +impl<'a> Deref for ValidatedOpening<'a> { + type Target = VerifiedOpening<'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +/// Checks every value of `opening` against the claimed model's shapes. +/// +/// An error that blames the node is a defect of the opening. Any other is +/// a header that does not name the model's shapes. +pub fn validate<'a>( + opening: VerifiedOpening<'a>, + weights: &WeightFile, +) -> Result> { + let shapes = ModelShapes::of(weights)?; + for (stage, opened) in opening.stages() { + check_stage(opened, weights, &shapes) + .with_context(|| format!("stage {}", stage.stage_index)) + .or_node_fault()?; + } + Ok(ValidatedOpening(opening)) +} + +fn check_stage(opened: &StageOpening, weights: &WeightFile, shapes: &ModelShapes) -> Result<()> { + // the tokens of a cached prefix are the node's, like the receipt's + if let Some(tokens) = shapes.tokens + && let Some(token) = opened + .prefix_tokens + .iter() + .find(|&&token| !u64::try_from(token).is_ok_and(|t| t < tokens)) + { + node_fault!("the prefix names token {token}; the claimed model embeds {tokens}"); + } + for layer in &opened.layers { + for leaf in &layer.leaves { + check_leaf(leaf, weights, shapes) + .with_context(|| format!("layer {}, position {}", layer.layer, leaf.position))?; + } + } + for anchor in &opened.anchors { + check_anchor(anchor, shapes).with_context(|| format!("position {}", anchor.position))?; + } + for head in &opened.head { + check_head(head, shapes).with_context(|| format!("position {}", head.position))?; + } + for partials in &opened.attention { + let values = partials.values()?; + ensure_node!( + all_finite(&values), + "position {}, layer {}: an attention partial is not a number", + partials.position, + partials.layer + ); + } + for region in &opened.recurrent { + for leaf in ®ion.leaves { + check_mixing(&leaf.mixing).with_context(|| { + format!( + "recurrent region of layer {}, position {}", + region.layer, leaf.position + ) + })?; + } + } + Ok(()) +} + +/// A residual of the model's width, of numbers alone. +fn check_residual(what: &str, values: &[f32], shapes: &ModelShapes) -> Result<()> { + ensure_node!( + values.len() == shapes.hidden, + "{what} has {} values; the model's residual stream has {}", + values.len(), + shapes.hidden + ); + ensure_node!( + all_finite(values), + "{what} holds a value that is not a number" + ); + Ok(()) +} + +fn check_leaf(leaf: &LeafOpening, weights: &WeightFile, shapes: &ModelShapes) -> Result<()> { + check_residual("the residual in", &leaf.residual_in_values()?, shapes)?; + if let Some(out) = leaf.residual_out_values()? { + check_residual("the residual out", &out, shapes)?; + } + check_mixing(&leaf.mixing)?; + // the experts a selection can pick are the ones the layer's expert + // weights hold + let mut experts: Option = None; + for m in &leaf.matrices { + let held = check_matrix(m, weights)?; + if m.experts.is_some() { + experts = Some(experts.map_or(held, |least| least.min(held))); + } + } + for selection in &leaf.selections { + let in_range = + |id: i32| u64::try_from(id).is_ok_and(|id| experts.is_none_or(|held| id < held)); + if let Some(id) = selection.ids.iter().find(|&&id| !in_range(id)) { + node_fault!( + "selection {} picks id {id}, outside the layer's {} experts", + selection.index, + experts.map_or("non-negative".to_owned(), |held| held.to_string()) + ); + } + } + Ok(()) +} + +/// A mixing leaf's values: a stored row in a type the auditor checks, in +/// whole blocks; every other value f32. All of numbers alone. +fn check_mixing(mixing: &[TensorOpening]) -> Result<()> { + for value in mixing { + let name = value.kind.tensor_kind().name(); + let Some(bytes) = value.bytes()? else { + continue; + }; + if value.kind == MixingKind::Stored { + crate::cache_types::decode_row(value.ggml_type, &bytes) + .with_context(|| format!("{name} {}", value.index))?; + continue; + } + ensure_node!( + value.ggml_type == crate::layer_tensors::GGML_F32 && bytes.len().is_multiple_of(4), + "{name} {} is not whole f32 values", + value.index + ); + ensure_node!( + all_finite(&crate::layer_tensors::decode_f32_bytes(&bytes)), + "{name} {} holds a value that is not a number", + value.index + ); + } + Ok(()) +} + +/// An opened matmul against the weight it names. Returns the matrices the +/// weight holds: its experts, or 1. +fn check_matrix(m: &MatrixOpening, weights: &WeightFile) -> Result { + let Some(tensor) = weights.tensors.get(&m.weight) else { + node_fault!( + "matmul {} names {:?}, a tensor the claimed GGUF does not have", + m.index, + m.weight + ); + }; + let (input, output) = (m.input_values()?, m.output_values()?); + check_matmul_shape(tensor, m, input.len(), output.len())?; + ensure_node!( + all_finite(&input) && all_finite(&output), + "{} is opened with a value that is not a number", + m.weight + ); + Ok(tensor.dims.get(2).copied().unwrap_or(1)) +} + +fn check_anchor(anchor: &AnchorOpening, shapes: &ModelShapes) -> Result<()> { + check_residual("the input of layer 0", &anchor.residual_values()?, shapes) +} + +fn check_head(head: &HeadOpening, shapes: &ModelShapes) -> Result<()> { + check_residual("the output residual", &head.residual_values()?, shapes)?; + let Some(logits) = head.logit_values()? else { + return Ok(()); + }; + ensure_node!( + logits.len() as u64 == shapes.vocabulary, + "{} logits are opened for {} tokens", + logits.len(), + shapes.vocabulary + ); + ensure_node!(all_finite(&logits), "a logit is not a number"); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/opened_values/tests.rs b/crates/skippy-receipts/src/opened_values/tests.rs new file mode 100644 index 00000000..9b1cc807 --- /dev/null +++ b/crates/skippy-receipts/src/opened_values/tests.rs @@ -0,0 +1,258 @@ +use super::*; +use crate::attention::opening::AttentionPartials; +use crate::binding::verify_paths; +use crate::layer_tensors::{GGML_F32, f32_bytes}; +use crate::node_fault::NodeFault; +use crate::toy_turn::{HIDDEN, Turn, VOCABULARY, weights}; +use crate::wire::{Challenge, Opening, encode_f32}; + +/// What a node changes in an honest opening. +type Change<'a> = Box; + +fn challenged(turn: &Turn) -> Challenge { + turn.challenge(&[(0, &[1, 3]), (1, &[0, 3])], &[2, 4]) +} + +/// Validates a canonical opening that `change` altered. The Merkle paths +/// no longer fit after a change, so this checks the stages directly, as +/// [`validate`] does after the paths passed. +fn check(change: impl FnOnce(&mut Opening)) -> Result<()> { + let turn = Turn::new(); + let mut opening = turn.open(&challenged(&turn)); + change(&mut opening); + let weights = weights(); + let shapes = ModelShapes::of(&weights)?; + opening + .stages + .iter() + .try_for_each(|stage| check_stage(stage, &weights, &shapes).or_node_fault()) +} + +fn fault(change: impl FnOnce(&mut Opening)) -> String { + let error = check(change).unwrap_err(); + assert!( + NodeFault::find(&error).is_some(), + "not blamed on the node: {error:#}" + ); + format!("{error:#}") +} + +fn leaf(opening: &mut Opening) -> &mut LeafOpening { + &mut opening.stages[1].layers[0].leaves[1] +} + +#[test] +fn an_honest_opening_fits_the_model() { + let turn = Turn::new(); + let challenge = challenged(&turn); + let opening = turn.open(&challenge); + let weights = weights(); + let shapes = ModelShapes::of(&weights).unwrap(); + assert_eq!( + shapes, + ModelShapes { + hidden: HIDDEN, + vocabulary: VOCABULARY as u64, + tokens: Some(VOCABULARY as u64), + } + ); + let verified = verify_paths(&turn.receipt, &challenge, &opening).unwrap(); + let validated = validate(verified, &weights).unwrap(); + // the checks read the verified opening through it + assert_eq!(validated.anchors().len(), 3); + check_tokens(&turn.receipt, &shapes).unwrap(); +} + +#[test] +fn a_value_that_is_not_a_number_is_the_nodes_fault() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let values = [1.0, bad, 0.5, 0.25]; + let residual = encode_f32(&values); + let changes: Vec<(&str, Change<'_>)> = vec![ + ( + "residual in", + Box::new(|o| leaf(o).residual_in = residual.clone()), + ), + ( + "residual out", + Box::new(|o| leaf(o).residual_out = Some(residual.clone())), + ), + ( + "matmul input", + Box::new(|o| leaf(o).matrices[0].input = residual.clone()), + ), + ( + "matmul output", + Box::new(|o| leaf(o).matrices[0].output = residual.clone()), + ), + ( + "mixing input", + Box::new(|o| { + let bytes = f32_bytes(&values); + leaf(o).mixing[0] = + TensorOpening::new(MixingKind::Input, 0, Some((GGML_F32, &bytes))); + }), + ), + ( + "mixing output", + Box::new(|o| { + let bytes = f32_bytes(&values); + leaf(o).mixing[2] = + TensorOpening::new(MixingKind::Output, 0, Some((GGML_F32, &bytes))); + }), + ), + ( + "stored row", + Box::new(|o| { + let bytes: Vec = values + .iter() + .flat_map(|&v| half::f16::from_f32(v).to_le_bytes()) + .collect(); + leaf(o).mixing[1] = + TensorOpening::new(MixingKind::Stored, 0, Some((1, &bytes))); + }), + ), + ( + "anchor", + Box::new(|o| o.stages[0].anchors[0].residual = residual.clone()), + ), + ( + "head residual", + Box::new(|o| o.stages[1].head[0].residual = residual.clone()), + ), + ( + "logits", + Box::new(|o| { + let mut logits = vec![0.5; VOCABULARY]; + logits[3] = bad; + o.stages[1].head[0].logits = Some(encode_f32(&logits)); + }), + ), + ( + "attention partials", + Box::new(|o| { + o.stages[1].attention = vec![AttentionPartials { + position: 3, + layer: 1, + head: 0, + partials: encode_f32(&[0.0, bad, 1.0]), + }]; + }), + ), + ]; + for (what, change) in changes { + let message = fault(change); + assert!( + message.contains("not a number"), + "{what} with {bad}: {message}" + ); + } + } +} + +#[test] +fn a_value_of_the_wrong_length_is_the_nodes_fault() { + let short = encode_f32(&[1.0, 2.0, 3.0]); + let long = encode_f32(&[1.0; 8]); + let message = fault(|o| leaf(o).residual_in = short.clone()); + assert!( + message.contains("layer 1, position 3: the residual in has 3 values"), + "{message}" + ); + fault(|o| leaf(o).residual_out = Some(long.clone())); + fault(|o| o.stages[0].anchors[1].residual = short.clone()); + fault(|o| o.stages[1].head[1].residual = long.clone()); + // a column that is not the weight's columns or rows + let message = fault(|o| leaf(o).matrices[0].input = short.clone()); + assert!( + message.contains("do not fit the claimed weight"), + "{message}" + ); + fault(|o| leaf(o).matrices[0].output = long.clone()); + fault(|o| leaf(o).matrices[1].output = short.clone().repeat(2)); + // an empty column would pass every comparison + fault(|o| { + leaf(o).matrices[0].input = String::new(); + leaf(o).matrices[0].output = String::new(); + }); + // one output slice per expert named + fault(|o| leaf(o).matrices[2].output = encode_f32(&[0.5; HIDDEN])); + // logits for another vocabulary + let message = fault(|o| o.stages[1].head[0].logits = Some(encode_f32(&[0.5; 7]))); + assert!( + message.contains("7 logits are opened for 8 tokens"), + "{message}" + ); + // bytes that are not whole values + fault(|o| leaf(o).residual_in = "AAAAAAA=".into()); + fault(|o| leaf(o).matrices[0].input = "not base64".into()); + fault(|o| { + leaf(o).mixing[0] = TensorOpening::new(MixingKind::Input, 0, Some((GGML_F32, &[0u8; 6]))); + }); + // a stored f16 row of an odd number of bytes + fault(|o| { + leaf(o).mixing[1] = TensorOpening::new(MixingKind::Stored, 0, Some((1, &[0u8; 7]))); + }); +} + +#[test] +fn an_id_out_of_range_is_the_nodes_fault() { + // an expert the weight does not hold + let message = fault(|o| leaf(o).matrices[2].experts = Some(vec![0, 3])); + assert!(message.contains("expert 3 outside 3 experts"), "{message}"); + fault(|o| leaf(o).matrices[2].experts = Some(vec![-1, 0])); + // experts on a weight that has none + fault(|o| leaf(o).matrices[0].experts = Some(vec![5])); + // a selected id past the layer's experts, which the auditor's own + // evaluation would index its expert weights with + let message = fault(|o| leaf(o).selections[0].ids = vec![0, 1, 3]); + assert!(message.contains("picks id 3"), "{message}"); + fault(|o| leaf(o).selections[0].ids = vec![-2, 1, 0]); + fault(|o| leaf(o).selections[0].ids = vec![i32::MAX]); +} + +#[test] +fn a_tensor_the_claimed_gguf_does_not_have_is_the_nodes_fault() { + let message = fault(|o| leaf(o).matrices[0].weight = "blk.1.other.weight".into()); + assert!( + message.contains("a tensor the claimed GGUF does not have"), + "{message}" + ); +} + +#[test] +fn a_stored_row_of_an_unknown_type_is_the_nodes_fault() { + // 39 is no ggml type, and q4_1 is one no stage stores rows in: neither + // may reach the native runtime as a cache type + for ggml_type in [39, 3, -1, i32::MAX] { + let message = fault(|o| leaf(o).mixing[1].ggml_type = ggml_type); + assert!( + message.contains("which the auditor does not decode"), + "{ggml_type}: {message}" + ); + } + // a mixing input may only be f32 + fault(|o| leaf(o).mixing[0].ggml_type = 1); +} + +#[test] +fn a_receipts_tokens_are_ones_the_model_embeds() { + let shapes = ModelShapes::of(&weights()).unwrap(); + for bad in [VOCABULARY as i32, -1, i32::MAX] { + let mut receipt = Turn::new().receipt; + receipt.tokens[2] = bad; + let error = check_tokens(&receipt, &shapes).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + let mut receipt = Turn::new().receipt; + receipt.final_token = Some(bad); + assert!(check_tokens(&receipt, &shapes).is_err(), "{bad}"); + } +} + +#[test] +fn a_header_without_the_models_shapes_blames_nobody() { + let bare = + crate::weights::test_gguf::open(&[], &[("output.weight", vec![4, 8], vec![0.0; 32])]); + let error = ModelShapes::of(&bare).unwrap_err(); + assert!(NodeFault::find(&error).is_none(), "{error:#}"); +} diff --git a/crates/skippy-receipts/src/recorder.rs b/crates/skippy-receipts/src/recorder.rs new file mode 100644 index 00000000..7ace0fc1 --- /dev/null +++ b/crates/skippy-receipts/src/recorder.rs @@ -0,0 +1,830 @@ +//! Node side: records each ubatch's committed leaves and a replay log per +//! native sequence, commits a turn to a Merkle root, and opens a challenge +//! by replaying the turn in a scratch context ("replay, not storage" in +//! RECEIPTS.md). +//! +//! Per position, a stage keeps only leaf hashes. Per ubatch, it keeps what +//! replay needs to reproduce it bit for bit: tokens, sequences, positions, +//! output rows, KV cells, n_kv, and the stage input rows of a stage after +//! the first. A turn's replay starts from the KV cells the turn attended to +//! below its first position, copied from the stage's cache, so it replays +//! only the turn's own ubatches, also after a shared cached prefix +//! ([`cells`]). A KV-cache change the replay cannot reproduce (a position +//! shift, a state load, compaction) makes the turn unreceiptable. +//! +//! A native sequence serves one request after another, so a log belongs to +//! a turn, not to a sequence: the session that computes a turn arms its +//! [`TurnId`] before its first ubatch ([`Recorder::begin_turn`]), and a +//! commit names that id. A commit never takes the log of another turn, +//! also when the sequence was reset and reused before the commit arrived. +//! +//! A replay costs about what serving the turn did, so a receipt is replayed +//! for at most [`MAX_REPLAYS_PER_RECEIPT`] distinct challenges, and a +//! repeated challenge is answered from the openings already made. + +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::ops::Range; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crate::commitment::{Hash, MerkleTree, slots_per_position}; +use crate::layer_tensors::{TensorKind, UbatchColumns}; +use crate::wire::{CannotOpen, CannotOpenReason}; + +/// Committed turns, and logs of turns that ended without a commit, are +/// dropped, oldest first, past this many bytes. +pub(crate) const DEFAULT_WINDOW_BYTES: usize = 1 << 30; +/// Input rows of recorded ubatches a stage after the first keeps for the +/// cells of its KV cache, so a turn that reads them as its cached prefix can +/// open one. Past this many bytes the oldest are dropped, and a turn that +/// reads their cells gets no receipt. +pub(crate) const DEFAULT_LINEAGE_INPUT_BYTES: usize = 1 << 30; +/// Distinct challenges a committed turn is replayed for, at most. +pub const MAX_REPLAYS_PER_RECEIPT: u32 = 4; +/// Logs of turns that ended before they were committed, kept per sequence. +const RETIRED_LOGS: usize = 4; +/// How long the log of a turn that ended without a commit waits for one. A +/// commit follows its turn at once, so a log this old has none coming. +const RETIRED_LOG_TTL: Duration = Duration::from_secs(60); +/// Token id of the dummy columns that stand in for other sequences in a replay. +const DUMMY_TOKEN: i32 = 0; + +mod answered_rows; +mod attention_opening; +mod cells; +mod challenge_shape; +mod event_log; +mod leaves; +mod lineage; +mod openings; +mod pins; +mod prefix_opening; +mod recurrent; +mod recurrent_opening; +mod replay; +mod stage_opening; +mod turn_commit; +mod turn_seed; + +use cells::{CellMirror, ColumnLeaves, TurnPrefix}; +pub use cells::{KvCell, KvStreams, MemoryOp, PrefixCell}; +use event_log::Event; +use leaves::PositionLeaves; +use openings::OpeningCache; +pub use pins::{CHALLENGE_PIN, FIRM_PIN, OPENING_PIN}; +pub use replay::{ + AnchorValue, ReplayAnchor, ReplayScope, ReplaySeed, ReplayStep, ReplayedLayer, ReplayedMatmul, + ReplayedMixing, ReplayedPosition, Replayer, StoredRows, +}; + +/// Names one turn of a native sequence. The session that computes the turn +/// arms it before the turn's first ubatch ([`Recorder::begin_turn`]) and +/// carries it to the commit, which takes that turn's log and no other's. +/// The default names what a sequence records before any session armed one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct TurnId(pub u64); + +impl std::fmt::Display for TurnId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +/// Stage input rows of a ubatch, for a stage after the first. +#[derive(Clone, Debug, PartialEq)] +pub struct StageInput { + pub rows: Vec, + pub row_bytes: usize, + /// ggml type of the rows. + pub ggml_type: i32, +} + +/// What replay needs to reproduce one computed ubatch, column per token. +#[derive(Clone, Debug, PartialEq)] +pub struct UbatchRecord { + pub token: Vec, + pub seq: Vec, + pub pos: Vec, + pub output: Vec, + pub cell: Vec, + pub n_kv: u32, + pub input: Option, +} + +impl UbatchRecord { + fn bytes(&self) -> usize { + self.token.len() * 21 + self.input.as_ref().map_or(0, |input| input.rows.len()) + } +} + +#[derive(Default)] +struct SeqLog { + /// The turn the log records. + turn: TurnId, + events: Vec, + /// Bytes of [`Self::events`], kept as they arrive so the window counts + /// a log before its turn commits ([`RecorderState::shed_live`]). + event_bytes: usize, + /// The log outgrew the window and its turn gets no receipt: it records + /// no more ubatches or positions until the sequence's next turn, and + /// keeps only its taint and a stand-in for its prefix + /// ([`RecorderState::shed_live`]). + shed: bool, + /// What the stage committed per position. + leaves: BTreeMap, + /// First position recorded since the last commit. + pending_start: Option, + /// Why the pending turn cannot be replayed. + tainted: Option, + /// A ubatch the recorder could not record ran while the log was live. + /// The native report does not say which sequences it computed, so the + /// turn commits only if its positions show it computed nothing the log + /// lacks: they start where the turn did, and every one was recorded. + missed: bool, + /// The cells the pending turn attended to below its first position, as + /// they were when its first ubatch was recorded, or why they are unknown. + prefix: Option>, + /// ggml types of the cache rows the stage stored. + cache_types: BTreeSet, + /// On a stage with hybrid memory, the recurrent state the pending turn + /// started from, or why it is unknown. + state: Option>, +} + +impl SeqLog { + fn of(turn: TurnId) -> Self { + Self { + turn, + ..Self::default() + } + } + + fn push_event(&mut self, event: Event) { + if self.shed { + return; + } + self.event_bytes += event.bytes(); + self.events.push(event); + } + + /// Takes the events, for a commit or a new turn. + fn take_events(&mut self) -> Vec { + self.event_bytes = 0; + self.shed = false; + std::mem::take(&mut self.events) + } + + /// Bytes a live log holds for its turn: its ubatches, with their input + /// rows, its recurrent state, the hashes it committed per position and + /// the cells of its prefix. Counted without a walk of the log, as every + /// ubatch asks it. + fn live_bytes(&self) -> usize { + let state = match &self.state { + Some(Ok(state)) => state.bytes_held(), + _ => 0, + }; + // every position of a stage holds as many hashes + let leaves = + self.leaves.values().next().map_or(0, PositionLeaves::bytes) * self.leaves.len(); + self.event_bytes + state + leaves + self.prefix_bytes() + } + + fn prefix_bytes(&self) -> usize { + match &self.prefix { + Some(Ok(prefix)) => prefix.bytes(), + _ => 0, + } + } + + fn pending(&self) -> Option> { + let start = self.pending_start?; + let (&last, _) = self.leaves.range(start..).next_back()?; + Some(start..last + 1) + } + + /// Whether the log holds a pending turn of `turn` that recorded every + /// one of `positions`, and, after a ubatch it could not record, starts + /// where they do ([`Self::missed`]). A commit is checked against it + /// before it takes the log, so one that names positions the log cannot + /// commit leaves the log for the commit that can. + fn covers(&self, turn: TurnId, positions: &Range) -> bool { + self.turn == turn + && self.pending_start.is_some_and(|start| { + start <= positions.start && (!self.missed || start == positions.start) + }) + && positions + .clone() + .all(|position| self.leaves.contains_key(&position)) + } + + /// Bytes the log holds. + fn bytes(&self) -> usize { + let events: usize = self.events.iter().map(Event::bytes).sum(); + let leaves: usize = self.leaves.values().map(PositionLeaves::bytes).sum(); + let state = match &self.state { + Some(Ok(state)) => state.bytes_held(), + _ => 0, + }; + events + leaves + state + self.prefix_bytes() + } +} + +/// The log of a turn that ended before it was committed. +struct RetiredLog { + log: SeqLog, + retired_at: Instant, + bytes: usize, +} + +#[derive(Default)] +struct SeqState { + live: SeqLog, + /// Logs of turns that ended before they were committed, newest last. + /// Each stays addressable by its turn until it is committed, expires or + /// is crowded out. + retired: VecDeque, +} + +impl SeqState { + fn taint(&mut self, reason: &str) { + self.live.tainted.get_or_insert_with(|| reason.to_string()); + } +} + +struct CommittedTurn { + receipt_id: String, + seq: i32, + position_start: u32, + position_end: u32, + /// The cells the replay starts from, with what the stage committed at + /// each of their positions. + prefix: TurnPrefix, + /// The runs that wrote the prefix cells, whose ubatches a replay of a + /// prefix position needs ([`CellMirror::lineage_runs`]). + lineage_runs: Vec, + events: Vec, + tree: MerkleTree, + /// By position from `position_start`, the cell the turn wrote it to. + cells: Vec, + /// The attention picks the stage opened partials for. + attention: Vec, + /// The rows requests answered, so a repeated request reads no rows + /// again and a lost answer can be asked for after the pin ends. + rows: answered_rows::RowsRequests, + bytes: usize, + /// Replays started for this turn. + replays: u32, + pin: pins::Pin, + /// On a stage with hybrid memory, the recurrent state the turn started + /// from. + state: Option, +} + +/// A turn position's cell: its digest, and per layer the half of the +/// mixing leaf that opens the stored rows ([`crate::commitment::mixing_rest`]). +struct TurnCell { + digest: Hash, + rests: Vec, +} + +#[derive(Default)] +struct RecorderState { + seqs: HashMap, + cells: CellMirror, + committed: VecDeque, + committed_bytes: usize, + /// Bytes of every retired log. + retired_bytes: usize, + openings: OpeningCache, + /// The cells the stage was last told to pin ([`Recorder::pinned_cells`]). + pins: BTreeSet, + /// Cells in a stream of the stage's KV cache; 0 when unknown + /// ([`Recorder::set_pin_budget`]). + pin_budget: u32, + last_error: Option, + /// Layers whose token mixing reads a recurrent state. + state_layers: BTreeSet, +} + +impl RecorderState { + /// Ends the live log of `seq`, whose next log is of `turn` (of the same + /// turn when `None`). A turn the log holds that was not committed is + /// kept, addressable by its turn, for the commit that may still come. + fn retire(&mut self, seq: i32, turn: Option, now: Instant) { + let entry = self.seqs.entry(seq).or_default(); + let turn = turn.unwrap_or(entry.live.turn); + let old = std::mem::replace(&mut entry.live, SeqLog::of(turn)); + if old.pending().is_none() { + return; + } + let bytes = old.bytes(); + self.retired_bytes += bytes; + entry.retired.push_back(RetiredLog { + log: old, + retired_at: now, + bytes, + }); + while entry.retired.len() > RETIRED_LOGS { + if let Some(dropped) = entry.retired.pop_front() { + self.retired_bytes -= dropped.bytes; + } + } + } + + /// Drops the retired logs no commit is still coming for. + fn drop_stale_logs(&mut self, now: Instant) { + for entry in self.seqs.values_mut() { + while entry + .retired + .front() + .is_some_and(|log| now.saturating_duration_since(log.retired_at) >= RETIRED_LOG_TTL) + { + if let Some(dropped) = entry.retired.pop_front() { + self.retired_bytes -= dropped.bytes; + } + } + } + } + + /// Drops the oldest retired log of any sequence; `false` when there is + /// none. + fn drop_oldest_retired(&mut self) -> bool { + let oldest = self + .seqs + .iter() + .filter_map(|(&seq, entry)| Some((entry.retired.front()?.retired_at, seq))) + .min(); + let Some((_, seq)) = oldest else { + return false; + }; + if let Some(dropped) = self + .seqs + .get_mut(&seq) + .and_then(|entry| entry.retired.pop_front()) + { + self.retired_bytes -= dropped.bytes; + } + true + } + + /// Bytes of every live log ([`SeqLog::live_bytes`]). + fn live_bytes(&self) -> usize { + self.seqs + .values() + .map(|entry| entry.live.live_bytes()) + .sum() + } + + fn held_bytes(&self) -> usize { + self.committed_bytes + self.retired_bytes + self.live_bytes() + } + + /// Keeps what the recorder holds within `window` bytes as far as it may: + /// logs nobody committed go first, then committed turns no client can + /// still challenge, then turns that linger in their challenge window + /// ([`pins::Pin::lingers`]), each oldest first. A turn held firmly + /// ([`pins::Pin::firm`]) is never dropped for room; a new turn that + /// does not fit beside them gets no receipt ([`Self::make_room`]), and + /// a live log that does not fit is shed ([`Self::shed_live`]). + fn enforce_window(&mut self, window: usize, now: Instant) { + while self.held_bytes() > window { + if self.drop_oldest_retired() { + continue; + } + let unheld = self.committed.iter().position(|t| !t.pin.holds(now)); + let droppable = + unheld.or_else(|| self.committed.iter().position(|t| t.pin.lingers(now))); + let Some(index) = droppable else { + break; + }; + if let Some(old) = self.committed.remove(index) { + self.committed_bytes -= old.bytes; + self.openings.forget(&old.receipt_id); + } + } + } + + /// Sheds live logs, largest first, while what the recorder holds is + /// past `window` after [`Self::enforce_window`]: a long or wide prefill + /// must not hold more than the window before its turn commits. A shed + /// log's turn gets no receipt; the sequence's next turn records again. + fn shed_live(&mut self, window: usize) { + while self.held_bytes() > window { + let largest = self + .seqs + .values_mut() + .map(|entry| &mut entry.live) + .filter(|log| log.live_bytes() > 0) + .max_by_key(|log| log.live_bytes()); + let Some(log) = largest else { + return; + }; + log.tainted.get_or_insert_with(|| { + format!("its replay log outgrew the recorder's window of {window} bytes") + }); + log.take_events(); + log.shed = true; + log.state = None; + // the turn gets no receipt, so its positions and prefix are + // not needed; the stand-in keeps its later ubatches in the turn + log.leaves.clear(); + log.pending_start = None; + log.prefix = Some(Err("the turn's log was shed".to_owned())); + } + } + + /// Makes room for a turn of `bytes` within `window`, or fails, dropping + /// no turn held firmly for a challenge. + fn make_room(&mut self, window: usize, bytes: usize, now: Instant) -> anyhow::Result<()> { + self.enforce_window(window.saturating_sub(bytes), now); + let held = self.held_bytes(); + if held + bytes > window { + anyhow::bail!( + "the stage holds {held} bytes of turns a client is challenging or may \ + challenge at once, of {window} at most; this turn of {bytes} bytes gets no \ + receipt" + ); + } + Ok(()) + } + + /// The runs whose ubatches the lineage budget keeps: those a turn held + /// firmly for a challenge replays a prefix position from. The runs of a + /// turn that lingers are kept like any other, while the budget has + /// room: kept past it, they would cost a newer turn its receipt. + fn lineage_in_window(&self, now: Instant) -> BTreeSet { + self.committed + .iter() + .filter(|turn| turn.pin.firm(now)) + .flat_map(|turn| turn.lineage_runs.iter().copied()) + .collect() + } + + /// Forgets the committed turns under `receipt_id` and their openings. + fn discard(&mut self, receipt_id: &str) { + let mut freed = 0; + self.committed.retain(|turn| { + let keep = turn.receipt_id != receipt_id; + if !keep { + freed += turn.bytes; + } + keep + }); + self.committed_bytes -= freed; + self.openings.forget(receipt_id); + } +} + +/// The committed turn under `receipt_id`. +fn turn<'a>(committed: &'a VecDeque, receipt_id: &str) -> Option<&'a CommittedTurn> { + committed.iter().rev().find(|t| t.receipt_id == receipt_id) +} + +fn turn_mut<'a>( + committed: &'a mut VecDeque, + receipt_id: &str, +) -> Option<&'a mut CommittedTurn> { + committed + .iter_mut() + .rev() + .find(|t| t.receipt_id == receipt_id) +} + +pub struct Recorder { + stage_index: u32, + layers: Range, + backend: String, + /// The stage holds the model's final layer, so it opens the residual + /// the output head reads. + holds_output: bool, + window_bytes: usize, + /// The stage has hybrid memory ([`Self::set_recurrent`]). + recurrent: AtomicBool, + state: Mutex, +} + +impl Recorder { + pub fn new(stage_index: u32, layers: Range, backend: impl Into) -> Self { + Self { + stage_index, + layers, + backend: backend.into(), + holds_output: false, + window_bytes: DEFAULT_WINDOW_BYTES, + recurrent: AtomicBool::new(false), + state: Mutex::new(RecorderState::default()), + } + } + + /// Marks the stage as the one holding the model's final layer. + pub fn holding_output(mut self, holds_output: bool) -> Self { + self.holds_output = holds_output; + self + } + + /// Sets the bytes of committed turns and uncommitted logs the recorder + /// keeps, in place of [`DEFAULT_WINDOW_BYTES`]. + pub fn with_window_bytes(mut self, window_bytes: usize) -> Self { + self.window_bytes = window_bytes; + self + } + + /// Sets the bytes of input rows the recorder keeps for the cells of the + /// stage's KV cache, in place of [`DEFAULT_LINEAGE_INPUT_BYTES`]. + pub fn with_lineage_input_bytes(self, bytes: usize) -> Self { + self.lock().cells.set_input_budget(bytes); + self + } + + pub fn stage_index(&self) -> u32 { + self.stage_index + } + + pub fn layers(&self) -> Range { + self.layers.clone() + } + + fn slots(&self) -> u64 { + slots_per_position(self.layers.start, self.layers.end) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, RecorderState> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The error of a challenge this stage can no longer open. + fn cannot_open( + &self, + receipt_id: &str, + reason: CannotOpenReason, + detail: impl Into, + ) -> anyhow::Error { + anyhow::Error::new(CannotOpen { + receipt_id: receipt_id.to_owned(), + stage_index: self.stage_index, + reason, + detail: detail.into(), + }) + } + + /// The committed turn a challenge of `receipt_id` opens. + fn opening_turn<'a>( + &self, + committed: &'a VecDeque, + receipt_id: &str, + ) -> anyhow::Result<&'a CommittedTurn> { + turn(committed, receipt_id).ok_or_else(|| self.expired(receipt_id)) + } + + fn opening_turn_mut<'a>( + &self, + committed: &'a mut VecDeque, + receipt_id: &str, + ) -> anyhow::Result<&'a mut CommittedTurn> { + turn_mut(committed, receipt_id).ok_or_else(|| self.expired(receipt_id)) + } + + fn expired(&self, receipt_id: &str) -> anyhow::Error { + self.cannot_open( + receipt_id, + CannotOpenReason::Expired, + format!("receipt {receipt_id} is not in the opening window"), + ) + } + + /// Whether the stage still holds the committed turn of `receipt_id`. + pub fn holds_turn(&self, receipt_id: &str) -> bool { + turn(&self.lock().committed, receipt_id).is_some() + } + + /// A session starts computing turn `turn` on `seq`. Call it in report + /// order, after every ubatch computed before the session took the + /// sequence and before the session's first: the ubatches that follow + /// are the turn's. A turn the sequence still holds uncommitted is kept + /// for its own commit. + pub fn begin_turn(&self, seq: i32, turn: TurnId) { + let now = Instant::now(); + let mut state = self.lock(); + if state + .seqs + .get(&seq) + .is_some_and(|entry| entry.live.turn == turn) + { + return; + } + state.retire(seq, Some(turn), now); + state.drop_stale_logs(now); + state.enforce_window(self.window_bytes, now); + } + + /// Records one computed ubatch: the leaves of every column, and the + /// ubatch in the replay log of every sequence it touched. + pub fn record_ubatch(&self, record: UbatchRecord, columns: &dyn UbatchColumns) { + let leaves = + leaves::ubatch_leaves(self.layers.clone(), &record.pos, &record.token, columns); + let cache_types = self.cache_types(columns); + let state_layers: Vec = self + .layers + .clone() + .filter(|&layer| columns.count(layer, TensorKind::MixingState) > 0) + .collect(); + let record = Arc::new(record); + let now = Instant::now(); + let mut guard = self.lock(); + let state = &mut *guard; + // the lineage of a turn a client can still challenge outlasts the + // input budget + let protected = state.lineage_in_window(now); + state.cells.protect_runs(protected); + state.state_layers.extend(state_layers); + let mut first: BTreeMap = BTreeMap::new(); + for (&seq, &pos) in record.seq.iter().zip(&record.pos) { + let p = first.entry(seq).or_insert(pos); + *p = (*p).min(pos); + } + for (&seq, &pos) in &first { + let log = &mut state.seqs.entry(seq).or_default().live; + if log.prefix.is_none() { + // a new turn: it replays from the cells it attends to now + log.take_events(); + log.tainted = None; + log.missed = false; + let end = u32::try_from(pos).unwrap_or(0); + log.prefix = Some(state.cells.prefix(seq, end).map_err(|e| format!("{e:#}"))); + } + log.push_event(Event::Ubatch(record.clone())); + log.cache_types.extend(&cache_types); + } + let mut committed = Vec::with_capacity(record.seq.len()); + for (col, leaf) in leaves.into_iter().enumerate() { + let seq = state.seqs.entry(record.seq[col]).or_default(); + committed.push(match leaf { + Ok((position, hashes)) => { + // the cell keeps the leaves, for a turn that reads it + // as its cached prefix + let column = ColumnLeaves { + cell: hashes.cell, + leaves: Arc::clone(&hashes.leaves), + position: hashes.position, + }; + let log = &mut seq.live; + if !log.shed { + log.leaves.insert(position, hashes); + log.pending_start = + Some(log.pending_start.map_or(position, |p| p.min(position))); + } + Some(column) + } + Err(error) => { + seq.taint(&format!("{error:#}")); + None + } + }); + } + state.cells.write_ubatch(&record, committed); + state.enforce_window(self.window_bytes, now); + state.shed_live(self.window_bytes); + } + + fn cache_types(&self, columns: &dyn UbatchColumns) -> BTreeSet { + self.layers + .clone() + .flat_map(|layer| { + (0..columns.count(layer, TensorKind::MixingStored)).filter_map(move |index| { + columns + .column(layer, TensorKind::MixingStored, index, 0) + .map(|c| c.ggml_type) + }) + }) + .collect() + } + + /// The recorder lost track of the stage: a report it could not apply, + /// or one it does not know. Every live sequence's pending turn is + /// tainted, and every cell something unseen may have written is + /// forgotten or exposed ([`CellMirror::unseen_write`]). + pub fn unreceiptable(&self, reason: &str) { + let mut state = self.lock(); + for seq in state.seqs.values_mut() { + seq.taint(reason); + } + let RecorderState { cells, pins, .. } = &mut *state; + cells.unseen_write(pins); + state.last_error = Some(reason.to_string()); + } + + /// The stage computed one ubatch the native recorder could not receipt, + /// such as one of image embeddings. The report names neither its + /// sequences nor its cells, so the damage is bounded by what such a + /// ubatch can touch: + /// + /// - The positions it computed are missing from the log of each + /// sequence it computed, so that sequence's turn has a gap, or its + /// prefix lacks cells, and gets no receipt. A turn of another + /// sequence attends only to its own cells and keeps its receipt. + /// Every live log is marked, so a turn that started before the ubatch + /// commits only from its first position ([`SeqLog::missed`]). + /// - It wrote cells no sequence held: a free cell that is not pinned is + /// forgotten, and a pinned one, which the cache takes only when + /// nothing else fits, is checked before an opening reads it + /// ([`CellMirror::unseen_write`]). + pub fn unrecorded_ubatch(&self, reason: &str) { + let mut state = self.lock(); + for seq in state.seqs.values_mut() { + seq.live.missed = true; + } + let RecorderState { cells, pins, .. } = &mut *state; + cells.unseen_write(pins); + state.last_error = Some(reason.to_string()); + } + + /// Sets how the stage's KV cache lays out its cells. Call it before the + /// first ubatch: the mirror forgets the cells it knew. + pub fn set_kv_streams(&self, streams: KvStreams) { + self.lock().cells.set_streams(streams); + } + + /// Mirrors a KV-cache operation (`skippy_receipt_memory_op`). + pub fn memory_op(&self, op: MemoryOp, seq: i32, seq_dst: i32, p0: i32, p1: i32) { + let now = Instant::now(); + let mut state = self.lock(); + let RecorderState { cells, pins, .. } = &mut *state; + cells.memory_op(op, (seq, seq_dst), (p0, p1), pins); + let all: Vec = state.seqs.keys().copied().collect(); + let targets = if seq < 0 { all.clone() } else { vec![seq] }; + let taint = |state: &mut RecorderState, seqs: &[i32], reason: &str| { + for &s in seqs { + state.seqs.entry(s).or_default().taint(reason); + } + }; + match op { + MemoryOp::Clear => all.iter().for_each(|&s| state.retire(s, None, now)), + MemoryOp::SeqRm if event_log::removes_all(p0, p1) => { + targets.iter().for_each(|&s| state.retire(s, None, now)); + } + MemoryOp::SeqRm => { + for s in targets { + let log = &mut state.seqs.entry(s).or_default().live; + log.push_event(Event::SeqRm { p0, p1 }); + log.leaves + .retain(|&position, _| !event_log::removes(p0, p1, position)); + } + } + // seq_cp: a turn that has not started takes the shared cells as + // its prefix; one in progress cannot replay the change + MemoryOp::SeqCp if seq != seq_dst => { + if let Some(entry) = state.seqs.get_mut(&seq_dst) + && entry.live.prefix.is_some() + { + entry.taint("the sequence took KV cells from another sequence mid-turn"); + } + } + MemoryOp::SeqKeep => all + .iter() + .filter(|&&s| s != seq) + .for_each(|&s| state.retire(s, None, now)), + MemoryOp::SeqShift => taint( + &mut state, + &targets, + "the sequence's positions were shifted", + ), + MemoryOp::StateRead => taint( + &mut state, + &targets, + "the sequence's KV cells were loaded from saved state", + ), + MemoryOp::Compact => taint(&mut state, &all, "the KV cache was compacted"), + MemoryOp::SeqCp => {} + } + state.enforce_window(self.window_bytes, now); + } + + /// Why the last unreceiptable ubatch could not be receipted. + pub fn last_error(&self) -> Option { + self.lock().last_error.clone() + } + + /// Positions turn `turn` of `seq` recorded since its last commit. + pub fn recorded_range(&self, seq: i32, turn: TurnId) -> Option> { + let state = self.lock(); + let entry = state.seqs.get(&seq)?; + let live = (entry.live.turn == turn) + .then(|| entry.live.pending()) + .flatten(); + live.or_else(|| { + entry + .retired + .iter() + .rev() + .filter(|retired| retired.log.turn == turn) + .find_map(|retired| retired.log.pending()) + }) + } +} + +#[cfg(test)] +#[path = "recorder/tests.rs"] +mod tests; diff --git a/crates/skippy-receipts/src/recorder/answered_rows.rs b/crates/skippy-receipts/src/recorder/answered_rows.rs new file mode 100644 index 00000000..eb689c38 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/answered_rows.rs @@ -0,0 +1,96 @@ +//! The rows requests a stage answered for a turn. +//! +//! A rows request reads stored rows from the live KV cache under the +//! runtime's lock, so a client that repeats one could hold that lock for +//! as long as it likes. A stage keeps each answer with its turn and gives +//! it again for the same picks, and reads rows for at most +//! [`MAX_ROWS_REQUESTS_PER_RECEIPT`] requests of one receipt. A kept answer +//! also lets a client whose answer was lost ask again after the turn's pin +//! ended and the cells were written. + +use anyhow::{Result, bail}; + +use super::{Recorder, turn_mut}; +use crate::attention::opening::{BlockChallenge, BlockPick, RowProof, StageRows}; + +/// Rows requests of one receipt a stage reads rows for. A client asks +/// once per challenge; the rest covers a retry that failed before an +/// answer was kept. +pub const MAX_ROWS_REQUESTS_PER_RECEIPT: u32 = 4; + +/// The rows requests of one committed turn. +#[derive(Default)] +pub(super) struct RowsRequests { + /// Requests the stage read rows for. + read: u32, + answered: Vec<(Vec, StageRows)>, +} + +impl Recorder { + /// The kept answer to `challenge`, if the stage answered it before. + pub(super) fn answered_rows(&self, challenge: &BlockChallenge) -> Result> { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, &challenge.receipt_id)?; + Ok(turn + .rows + .answered + .iter() + .find(|(picks, _)| picks == &challenge.picks) + .map(|(_, rows)| rows.clone())) + } + + /// Counts a read of rows for a request of `receipt_id`, or refuses it + /// past [`MAX_ROWS_REQUESTS_PER_RECEIPT`]. + pub(super) fn count_rows_read(&self, receipt_id: &str) -> Result<()> { + let mut state = self.lock(); + let turn = self.opening_turn_mut(&mut state.committed, receipt_id)?; + if turn.rows.read >= MAX_ROWS_REQUESTS_PER_RECEIPT { + bail!( + "the stage already read rows for {MAX_ROWS_REQUESTS_PER_RECEIPT} requests of \ + receipt {receipt_id}" + ); + } + turn.rows.read += 1; + Ok(()) + } + + /// Keeps the answer to `challenge` with its turn, counted in the + /// turn's bytes. + pub(super) fn keep_rows(&self, challenge: &BlockChallenge, rows: &StageRows) { + let mut guard = self.lock(); + let state = &mut *guard; + let Some(turn) = turn_mut(&mut state.committed, &challenge.receipt_id) else { + return; + }; + let bytes = rows_bytes(rows); + turn.rows + .answered + .push((challenge.picks.clone(), rows.clone())); + turn.bytes += bytes; + state.committed_bytes += bytes; + } +} + +fn rows_bytes(rows: &StageRows) -> usize { + let paths = |path: &[String]| path.iter().map(String::len).sum::(); + rows.rows + .iter() + .map(|row| { + let stored: usize = row + .stored + .iter() + .map(|t| t.values.as_ref().map_or(0, String::len)) + .sum(); + let proof = match &row.proof { + RowProof::Turn { rest, path } => rest.len() + paths(path), + RowProof::Prefix { + cell_path, + leaves, + prefix_path, + .. + } => paths(cell_path) + leaves.len() + paths(prefix_path), + }; + stored + proof + }) + .sum() +} diff --git a/crates/skippy-receipts/src/recorder/attention_opening.rs b/crates/skippy-receipts/src/recorder/attention_opening.rs new file mode 100644 index 00000000..86781b0f --- /dev/null +++ b/crates/skippy-receipts/src/recorder/attention_opening.rs @@ -0,0 +1,480 @@ +//! A stage's side of the attention check ([`crate::attention`]). +//! +//! With the challenge, the stage opens the partials of each attention pick +//! in its layers: it reads the K and V rows of every position the query +//! attends to from its KV cache, and computes the picked head's partials +//! from them and the committed q, on its CPU. After the client picks the +//! blocks it recomputes, the stage opens their rows with proofs: through +//! the mixing leaf for a position the turn computed, and through the cell's +//! digest and the prefix root for one it read from cache. +//! +//! The rows are read from the live cache, so they are there only while the +//! cells still hold what the turn read or wrote; the stage checks that +//! before it reads. A freed cell keeps its rows until a ubatch writes it, +//! and the stage pins the cells of a turn a client may still challenge +//! ([`super::pins`]), so a later request writes other cells while it fits +//! there. + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Instant; + +use anyhow::{Context, Result, ensure}; + +use super::event_log::last_writes; +use super::stage_opening::name_receipt; +use super::{CommittedTurn, PrefixCell, Recorder, ReplayedLayer, Replayer, StoredRows, turn_mut}; +use crate::attention::opening::{ + AttentionPartials, AttentionPick, BlockChallenge, RowOpening, RowProof, StageRows, + stored_digests, +}; +use crate::attention::{ + AttentionLayout, BLOCKS_PER_PICK, ContextRow, block_positions, blocks, context_positions, + head_partials, layer_layout, +}; +use crate::commitment::{ + Hash, MerkleTree, encode_path, leaf_index, mixing_leaf_from, mixing_slot, slots_per_position, + stored_leaf, +}; +use crate::wire::{CannotOpenReason, LayerOpening, MixingKind, TensorOpening}; + +use super::cells::{CellRecord, prefix_leaves}; + +/// An attention pick a stage opened partials for: the positions its query +/// attends to, whose blocks the client may then ask the rows of. +#[derive(Clone, Debug)] +pub(super) struct OpenedAttention { + position: u32, + layer: u32, + context: Vec, +} + +/// Replayed values by (position, layer). +type Replayed = BTreeMap<(u32, u32), ReplayedLayer>; + +impl Recorder { + /// The partials of each attention pick of `picks` in this stage's + /// layers that has attention, from the opened q and the rows in the + /// stage's cache. + pub(super) fn open_attention( + &self, + receipt_id: &str, + picks: &[AttentionPick], + layers: &[LayerOpening], + replayed: &Replayed, + replayer: &dyn Replayer, + ) -> Result> { + let mut by_layer: BTreeMap> = BTreeMap::new(); + for pick in picks.iter().filter(|p| self.layers.contains(&p.layer)) { + let values = replayed + .get(&(pick.position, pick.layer)) + .with_context(|| format!("position {} was not replayed", pick.position))?; + // the client decides from its own build what a layer without a + // layout the check follows means + if let Ok(Some(layout)) = layer_layout(&values.attention) { + by_layer + .entry(pick.layer) + .or_default() + .push((pick, layout.clone())); + } + } + let mut partials = Vec::new(); + let mut opened = Vec::new(); + for (layer, picks) in by_layer { + let last = picks.iter().map(|(p, _)| p.position).max().unwrap_or(0); + let cells = self.context_cells(receipt_id, 0..last + 1)?; + self.verify_exposed(replayer, &cells)?; + self.check_cells(&cells)?; + let rows = read_context(replayer, layer, &cells, &picks[0].1)?; + for (pick, layout) in picks { + let leaf = layers + .iter() + .find(|l| l.layer == layer) + .and_then(|l| l.leaves.iter().find(|leaf| leaf.position == pick.position)) + .context("an attention pick outside the opened positions")?; + let q = layout.q_values(&leaf.mixing)?; + let head = pick.head_draw % u32::try_from(layout.op.n_head)?; + let context = context_positions(&layout.op, pick.position); + let values = + head_partials(&layout.op, head as usize, &q, &attended(&rows, &context))?; + partials.push(AttentionPartials::new(pick, head, &values)); + opened.push(OpenedAttention { + position: pick.position, + layer, + context, + }); + } + } + let mut state = self.lock(); + if let Some(turn) = turn_mut(&mut state.committed, receipt_id) { + turn.pin.opened(Instant::now(), !opened.is_empty()); + turn.attention.extend(opened); + } + drop(state); + Ok(partials) + } + + /// The cell that held each position in `positions` for the turn, with + /// its digest: a prefix cell below the turn, else the one the turn + /// wrote last. + fn context_cells( + &self, + receipt_id: &str, + positions: impl IntoIterator, + ) -> Result> { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, receipt_id)?; + let written = written_cells(turn); + positions + .into_iter() + .map(|position| { + if let Some(cell) = turn.prefix.cells.get(position as usize) { + return Ok(*cell); + } + let index = position + .checked_sub(turn.position_start) + .context("a position between the prefix and the turn")?; + let digest = turn + .cells + .get(index as usize) + .with_context(|| format!("position {position} is after the turn"))? + .digest; + let cell = *written + .get(&position) + .with_context(|| format!("the turn wrote no cell for position {position}"))?; + Ok(PrefixCell { + pos: i32::try_from(position)?, + stream: state.cells.streams().of(turn.seq), + cell, + digest, + }) + }) + .collect() + } + + /// Opens the rows of the blocks the client picked in this stage's + /// layers. Each pick must be one this stage opened partials for, and + /// name at most [`BLOCKS_PER_PICK`] of its blocks. + pub fn open_rows( + &self, + challenge: &BlockChallenge, + replayer: &dyn Replayer, + ) -> Result { + let opened = match self.answered_rows(challenge) { + Ok(Some(rows)) => Ok(rows), + Ok(None) => self + .open_requested_rows(challenge, replayer) + .inspect(|rows| self.keep_rows(challenge, rows)), + Err(error) => Err(error), + }; + opened.map_err(|error| name_receipt(error, &challenge.receipt_id)) + } + + fn open_requested_rows( + &self, + challenge: &BlockChallenge, + replayer: &dyn Replayer, + ) -> Result { + let wanted = self.requested_rows(challenge)?; + self.count_rows_read(&challenge.receipt_id)?; + let (prefix_len, prefix_tree, position_digests) = { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, &challenge.receipt_id)?; + let tree = if turn.prefix.is_empty() { + None + } else { + Some(MerkleTree::new(prefix_leaves(&turn.prefix))?) + }; + let digests: BTreeMap = wanted + .values() + .flatten() + .filter_map(|&p| Some((p, *turn.prefix.positions.get(p as usize)?))) + .collect(); + (turn.prefix.len() as u32, tree, digests) + }; + // a prefix cell's digest is over every layer of the stage, so its + // rows are read once for all the layers the challenge names + let prefix_positions: BTreeSet = wanted + .values() + .flatten() + .copied() + .filter(|&p| p < prefix_len) + .collect(); + let prefix = self.context_cells(&challenge.receipt_id, prefix_positions)?; + self.verify_exposed(replayer, &prefix)?; + self.check_cells(&prefix)?; + let prefix_trees = self.prefix_trees(replayer, &prefix)?; + let mut rows = Vec::new(); + for (layer, positions) in wanted { + let cells = self.context_cells(&challenge.receipt_id, positions)?; + self.verify_exposed(replayer, &cells)?; + self.check_cells(&cells)?; + let stored = replayer.read_rows(layer, &cells)?; + let index = u64::from(layer - self.layers.start); + for (i, cell) in cells.iter().enumerate() { + let position = u32::try_from(cell.pos)?; + let opened: Vec = stored + .iter() + .enumerate() + .map(|(index, rows)| { + TensorOpening::new( + MixingKind::Stored, + index as u32, + Some((rows.ggml_type, rows.row(i))), + ) + }) + .collect(); + let proof = match ( + &prefix_tree, + prefix_trees.get(&position), + position_digests.get(&position), + ) { + (Some(tree), Some(cell_tree), Some(leaves)) => RowProof::Prefix { + cell: cell.cell, + cell_path: encode_path(&cell_tree.path(index)?), + leaves: hex::encode(leaves), + prefix_path: encode_path(&tree.path(u64::from(position))?), + }, + _ => self.turn_proof(&challenge.receipt_id, position, layer, &opened)?, + }; + rows.push(RowOpening { + position, + layer, + stored: opened, + proof, + }); + } + } + self.release_pin(&challenge.receipt_id); + Ok(StageRows { + stage_index: self.stage_index, + rows, + }) + } + + /// The positions whose rows the challenge asks for, by layer. + fn requested_rows(&self, challenge: &BlockChallenge) -> Result>> { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, &challenge.receipt_id)?; + let mut wanted: BTreeMap> = BTreeMap::new(); + for pick in challenge + .picks + .iter() + .filter(|p| self.layers.contains(&p.layer)) + { + let opened = turn + .attention + .iter() + .find(|a| a.position == pick.position && a.layer == pick.layer) + .with_context(|| { + format!( + "no partials were opened at position {}, layer {}", + pick.position, pick.layer + ) + })?; + let distinct: BTreeSet = pick.blocks.iter().copied().collect(); + ensure!( + distinct.len() == pick.blocks.len() && distinct.len() <= BLOCKS_PER_PICK, + "at most {BLOCKS_PER_PICK} distinct blocks per pick" + ); + let n_blocks = blocks(opened.context.len()); + for &block in &distinct { + ensure!( + (block as usize) < n_blocks, + "block {block} is past the context" + ); + wanted + .entry(pick.layer) + .or_default() + .extend(block_positions(&opened.context, block)); + } + } + Ok(wanted + .into_iter() + .map(|(layer, positions)| (layer, positions.into_iter().collect())) + .collect()) + } + + /// The tree over the stored leaf of every layer of the stage in each + /// prefix cell, by position, checked against the digest the turn read. + pub(super) fn prefix_trees( + &self, + replayer: &dyn Replayer, + prefix: &[PrefixCell], + ) -> Result> { + self.cell_trees(prefix, |layer, cells| replayer.read_rows(layer, cells)) + } + + /// Checks the rows of every exposed cell among `cells` against its + /// digest ([`super::cells::CellRecord::Exposed`]), and clears the mark of + /// those that match. A cell that does not match fails as overwritten. + /// It reads every layer of the stage for those cells only, so it costs + /// nothing until a write the recorder did not see reached a pinned cell. + pub(super) fn verify_exposed( + &self, + replayer: &dyn Replayer, + cells: &[PrefixCell], + ) -> Result<()> { + let exposed: Vec = { + let state = self.lock(); + let mut exposed: Vec = cells + .iter() + .filter(|cell| state.cells.record(cell) == CellRecord::Exposed) + .copied() + .collect(); + exposed.sort_by_key(|cell| (cell.stream, cell.cell)); + exposed.dedup_by_key(|cell| (cell.stream, cell.cell)); + exposed + }; + for stream in exposed.chunk_by(|a, b| a.stream == b.stream) { + self.cell_trees(stream, |layer, cells| { + replayer.read_rows_to_check(layer, cells) + })?; + let mut state = self.lock(); + for cell in stream { + state.cells.clear_exposed(cell); + } + } + Ok(()) + } + + /// The tree over the stored leaf of every layer of the stage in each + /// cell, by position, checked against the cell's digest, from the rows + /// `read` returns. + fn cell_trees( + &self, + prefix: &[PrefixCell], + read: impl Fn(u32, &[PrefixCell]) -> Result>, + ) -> Result> { + if prefix.is_empty() { + return Ok(BTreeMap::new()); + } + let mut leaves: Vec> = vec![Vec::new(); prefix.len()]; + for l in self.layers.clone() { + let stored = read(l, prefix)?; + for (i, cell) in prefix.iter().enumerate() { + let digests = stored_digests(&cell_openings(&stored, i))?; + leaves[i].push(stored_leaf(u32::try_from(cell.pos)?, l, &digests)); + } + } + prefix + .iter() + .zip(leaves) + .map(|(cell, leaves)| { + // a cell's digest is the root of this tree + let tree = MerkleTree::new(leaves)?; + if tree.root() != cell.digest { + return Err(self.cannot_open( + "", + CannotOpenReason::CellsOverwritten, + format!( + "the cell at position {} no longer holds the rows the turn read", + cell.pos + ), + )); + } + Ok((u32::try_from(cell.pos)?, tree)) + }) + .collect() + } + + /// The proof of a stored row the turn computed: the rest of its mixing + /// leaf and the leaf's path. + fn turn_proof( + &self, + receipt_id: &str, + position: u32, + layer: u32, + stored: &[TensorOpening], + ) -> Result { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, receipt_id)?; + let rest = turn + .cells + .get((position - turn.position_start) as usize) + .and_then(|c| c.rests.get((layer - self.layers.start) as usize)) + .context("no mixing leaf at the position")?; + let slots = slots_per_position(self.layers.start, self.layers.end); + let index = leaf_index( + position, + mixing_slot(layer, self.layers.start), + turn.position_start, + slots, + ); + let leaf = mixing_leaf_from( + position, + layer, + rest, + &stored_leaf(position, layer, &stored_digests(stored)?), + ); + if turn.tree.leaf(index) != Some(leaf) { + return Err(self.cannot_open( + receipt_id, + CannotOpenReason::CellsOverwritten, + format!("the cell of position {position} no longer holds the rows the turn wrote"), + )); + } + Ok(RowProof::Turn { + rest: hex::encode(rest), + path: encode_path(&turn.tree.path(index)?), + }) + } +} + +/// The K and V rows of the cells, by position from 0. +fn read_context( + replayer: &dyn Replayer, + layer: u32, + cells: &[PrefixCell], + layout: &AttentionLayout, +) -> Result> { + let stored = replayer.read_rows(layer, cells)?; + cells + .iter() + .enumerate() + .map(|(i, cell)| { + let rows: Vec<(i32, &[u8])> = stored.iter().map(|s| (s.ggml_type, s.row(i))).collect(); + layout.context_row(u32::try_from(cell.pos)?, &rows) + }) + .collect() +} + +/// The stored rows of cell `i`, as openings. +fn cell_openings(stored: &[StoredRows], i: usize) -> Vec { + stored + .iter() + .enumerate() + .map(|(index, rows)| { + TensorOpening::new( + MixingKind::Stored, + index as u32, + Some((rows.ggml_type, rows.row(i))), + ) + }) + .collect() +} + +/// The rows of the attended positions: a slice of `rows` when the +/// positions are consecutive, as every attention window keeps them. +fn attended<'a>(rows: &'a [ContextRow], context: &[u32]) -> Cow<'a, [ContextRow]> { + match (context.first(), context.last()) { + (Some(&lo), Some(&hi)) if (hi - lo) as usize + 1 == context.len() => { + Cow::Borrowed(&rows[lo as usize..=hi as usize]) + } + _ => Cow::Owned(context.iter().map(|&p| rows[p as usize].clone()).collect()), + } +} + +/// The cell each position of the turn's sequence was last written to, for +/// every position the turn did not remove after. +pub(super) fn written_cells(turn: &CommittedTurn) -> BTreeMap { + last_writes(&turn.events, turn.seq) + .into_iter() + .filter_map(|(position, written)| { + Some(( + position, + turn.events[written.event].ubatch()?.cell[written.col], + )) + }) + .collect() +} diff --git a/crates/skippy-receipts/src/recorder/attention_tests.rs b/crates/skippy-receipts/src/recorder/attention_tests.rs new file mode 100644 index 00000000..92dd0a9a --- /dev/null +++ b/crates/skippy-receipts/src/recorder/attention_tests.rs @@ -0,0 +1,419 @@ +//! The stage's side of the attention check, on the test model of +//! `tests.rs`: one head over its three-value stored row, which serves as +//! both K and V. + +use std::collections::BTreeMap; + +use super::*; +use crate::attention::opening::{ + AttentionPick, BlockChallenge, BlockPick, ROWS_PIN, RowProof, RowsOpening, +}; +use crate::attention::{AttentionLayout, AttentionOp, BLOCK_POSITIONS, Window}; +use crate::attention_check::{ + block_challenge, block_passed, check_blocks, check_partials, verify_rows, +}; +use crate::recorder::answered_rows::MAX_ROWS_REQUESTS_PER_RECEIPT; +use crate::wire::{LeafOpening, Opening}; + +fn layout(layer: u32) -> AttentionLayout { + AttentionLayout { + layer, + op: AttentionOp { + n_head: 1, + n_head_kv: 1, + head_dim_k: 3, + head_dim_v: 3, + scale: 0.01, + softcap: 0.0, + sinks: None, + window: Window::Causal, + output_rotation: None, + q_rounding: None, + }, + q_input: 0, + k_store: 0, + v_store: 0, + output: 0, + output_gate: None, + } +} + +fn leaf(opening: &Opening, layer: u32, position: u32) -> &LeafOpening { + opening + .stages + .iter() + .flat_map(|s| &s.layers) + .find(|l| l.layer == layer) + .and_then(|l| l.leaves.iter().find(|leaf| leaf.position == position)) + .expect("an opened leaf") +} + +/// Opens `pick` with the challenge, then the rows of its blocks, and +/// checks them as a client would. Returns the rows opening. +fn open_and_check( + recorder: &Recorder, + replayer: &FakeReplayer, + receipt: &Receipt, + mut challenge: Challenge, + pick: AttentionPick, +) -> RowsOpening { + let layer = pick.layer; + challenge.attention = vec![pick.clone()]; + let stage = recorder.open(&challenge, replayer).unwrap(); + assert_eq!(stage.attention.len(), 1); + // an opened turn stays pinned until its rows can no longer be asked for + let later = std::time::Instant::now() + ROWS_PIN - std::time::Duration::from_secs(1); + assert!(!recorder.pinned_cells(later).is_empty()); + let opening = Opening { + receipt_id: challenge.receipt_id.clone(), + stages: vec![stage.clone()], + }; + let layout = layout(layer); + let leaf = leaf(&opening, layer, pick.position); + let head = check_partials(&layout, &pick, leaf, &stage.attention[0]).unwrap(); + assert_eq!(head.context.len(), pick.position as usize + 1); + let blocks = block_challenge(&challenge.receipt_id, std::slice::from_ref(&head), b"seed"); + let rows = RowsOpening { + receipt_id: challenge.receipt_id.clone(), + stages: vec![recorder.open_rows(&blocks, replayer).unwrap()], + }; + assert!(recorder.pinned_cells(later).is_empty()); + let layouts = BTreeMap::from([(layer, layout.clone())]); + let context = verify_rows(receipt, &layouts, &rows).unwrap(); + let q = layout.q_values(&leaf.mixing).unwrap(); + let error = check_blocks(&layout, &head, &blocks.picks[0], &q, &context).unwrap(); + assert!(block_passed(error), "block error {error}"); + rows +} + +fn with_attention(mut replayer: FakeReplayer, layer: u32) -> FakeReplayer { + replayer.attention = Some(layout(layer)); + replayer +} + +#[test] +fn a_turn_opens_partials_and_the_rows_it_computed() { + let mut node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + node.replayers[1] = with_attention(FakeReplayer::for_stage(1), 3); + let pick = AttentionPick { + position: 3, + layer: 3, + head_draw: 5, + }; + let rows = open_and_check( + &node.stages[1], + &node.replayers[1], + &receipt, + challenge(&[(3, &[1, 3])]), + pick, + ); + let opened = &rows.stages[0].rows; + assert_eq!(opened.len(), 4, "the one block holds every position"); + assert!( + opened + .iter() + .all(|r| matches!(r.proof, RowProof::Turn { .. })) + ); + + // a changed row no longer hashes to its leaf + let mut forged = rows.clone(); + let row = &mut forged.stages[0].rows[2]; + let mut bytes = row.stored[0].bytes().unwrap().unwrap(); + bytes[0] ^= 1; + row.stored[0] = TensorOpening::new(MixingKind::Stored, 0, Some((CACHE_TYPE, &bytes))); + let layouts = BTreeMap::from([(3, layout(3))]); + assert!(verify_rows(&receipt, &layouts, &forged).is_err()); +} + +// A client that repeats a rows request gets the kept answer, and the stage +// reads no rows for it: not while it holds the runtime's lock, and not after +// the cells were written. Past the cap, a request that needs a read is +// refused. +#[test] +fn a_repeated_rows_request_reads_no_rows_again() { + let mut node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + node.replayers[1] = with_attention(FakeReplayer::for_stage(1), 3); + let pick = AttentionPick { + position: 3, + layer: 3, + head_draw: 5, + }; + let (recorder, replayer) = (&node.stages[1], &node.replayers[1]); + let first = open_and_check( + recorder, + replayer, + &receipt, + challenge(&[(3, &[1, 3])]), + pick, + ); + let blocks = BlockChallenge { + receipt_id: receipt.receipt_id.clone(), + picks: vec![BlockPick { + position: 3, + layer: 3, + blocks: vec![0], + }], + proof: None, + }; + let reads = replayer.row_reads.get(); + for _ in 0..100 { + assert_eq!( + recorder.open_rows(&blocks, replayer).unwrap(), + first.stages[0] + ); + } + assert_eq!(replayer.row_reads.get(), reads); + // the turn's cells are written; the kept answer still opens the rows + recorder.memory_op(MemoryOp::SeqRm, 7, -1, -1, -1); + record( + recorder, + ubatch(&[(5, 0), (5, 1), (5, 2), (5, 3)], &[0, 1, 2, 3], true), + ); + assert_eq!( + recorder.open_rows(&blocks, replayer).unwrap(), + first.stages[0] + ); + + for _ in 1..MAX_ROWS_REQUESTS_PER_RECEIPT { + recorder.count_rows_read(&receipt.receipt_id).unwrap(); + } + let error = recorder.count_rows_read(&receipt.receipt_id).unwrap_err(); + assert!( + format!("{error:#}").contains("already read rows"), + "{error:#}" + ); +} + +#[test] +fn a_cached_prefix_opens_its_rows_through_the_prefix_root() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a cached prompt of seventy positions, which another sequence continues + let prompt: Vec<(i32, i32)> = (0..70).map(|p| (3, p)).collect(); + let cells: Vec = (0..70).collect(); + record(&recorder, ubatch(&prompt, &cells, true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 70), (1, 71)], &[70, 71], true)); + let commitment = recorder.commit("r1", 1, TurnId::default(), 70..72).unwrap(); + let receipt = Receipt { + version: RECEIPT_VERSION, + receipt_id: "r1".into(), + model: "m".into(), + position_start: 70, + position_end: 72, + tokens: vec![1070, 1071], + generation_start: 71, + final_token: None, + stages: vec![commitment], + binding: None, + }; + let replayer = with_attention(FakeReplayer::for_stage(1), 2); + let pick = AttentionPick { + position: 71, + layer: 2, + head_draw: 0, + }; + let rows = open_and_check( + &recorder, + &replayer, + &receipt, + challenge(&[(2, &[71])]), + pick, + ); + // two blocks of 72 positions: both are drawn, so every row is opened + let opened = &rows.stages[0].rows; + assert_eq!(opened.len(), 72); + const { assert!(BLOCK_POSITIONS < 72) }; + let prefix = opened + .iter() + .filter(|r| matches!(r.proof, RowProof::Prefix { .. })) + .count(); + assert_eq!(prefix, 70); + + // a block the stage did not open partials for is refused + let unasked = BlockChallenge { + receipt_id: "r1".into(), + picks: vec![BlockPick { + position: 70, + layer: 2, + blocks: vec![0], + }], + proof: None, + }; + assert!(recorder.open_rows(&unasked, &replayer).is_err()); + let past = BlockChallenge { + receipt_id: "r1".into(), + picks: vec![BlockPick { + position: 71, + layer: 2, + blocks: vec![2], + }], + proof: None, + }; + assert!(recorder.open_rows(&past, &replayer).is_err()); + + // once a prefix cell is reused, its rows cannot be opened + recorder.memory_op(MemoryOp::SeqRm, 3, -1, -1, -1); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + record(&recorder, ubatch(&[(5, 0)], &[1], true)); + let again = BlockChallenge { + receipt_id: "r1".into(), + picks: vec![BlockPick { + position: 71, + layer: 2, + blocks: vec![0], + }], + proof: None, + }; + assert!(recorder.open_rows(&again, &replayer).is_err()); +} + +/// The pinned cells, all of the one stream. +fn cells(recorder: &Recorder, now: std::time::Instant) -> Vec { + let pinned = recorder.pinned_cells(now); + assert!(pinned.iter().all(|c| c.stream == 0)); + pinned.iter().map(|c| c.cell).collect() +} + +#[test] +fn a_recent_turn_pins_the_cells_its_attention_reads() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a cached prompt of three positions, which another sequence continues + let prompt: Vec<(i32, i32)> = (0..3).map(|p| (3, p)).collect(); + record(&recorder, ubatch(&prompt, &[10, 11, 12], true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 3), (1, 4)], &[13, 14], true)); + recorder.commit("r1", 1, TurnId::default(), 3..5).unwrap(); + let now = std::time::Instant::now(); + assert_eq!(cells(&recorder, now), vec![10, 11, 12, 13, 14]); + + // freed cells keep their rows, so they stay pinned + recorder.memory_op(MemoryOp::SeqRm, -1, -1, -1, -1); + assert_eq!(cells(&recorder, now), vec![10, 11, 12, 13, 14]); + // a cell another request wrote holds nothing of the turn + record(&recorder, ubatch(&[(2, 0)], &[11], true)); + assert_eq!(cells(&recorder, now), vec![10, 12, 13, 14]); + // and once the challenge window passes, nothing is pinned + assert!(recorder.pinned_cells(now + CHALLENGE_PIN).is_empty()); +} + +#[test] +fn a_turn_no_client_can_challenge_pins_nothing() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[4, 5], true)); + recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + let now = std::time::Instant::now(); + assert_eq!(cells(&recorder, now), vec![4, 5]); + recorder.release_pin("r1"); + assert!(recorder.pinned_cells(now).is_empty()); +} + +// Each challenge holds the turn for its own opening: a duplicate that is +// turned away, and ends first, does not release the cells one being +// replayed still needs. +#[test] +fn a_challenge_turned_away_keeps_the_pin_of_one_being_opened() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[4, 5], true)); + recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + let now = std::time::Instant::now(); + let past_window = now + CHALLENGE_PIN; + let arrived = past_window - std::time::Duration::from_secs(2); + // the first is being replayed when a duplicate arrives and is refused + recorder.hold_for_opening("r1", arrived); + recorder.hold_for_opening("r1", arrived); + recorder.end_opening("r1"); + assert_eq!(cells(&recorder, past_window), vec![4, 5]); + // once the replayed one ends, the pin it held is gone + recorder.end_opening("r1"); + assert!(recorder.pinned_cells(past_window).is_empty()); +} + +// A challenge that arrives while its turn is pinned keeps the turn's cells +// pinned until the opening ends, also past the challenge pin: the opening +// reads them after the replay, which takes seconds for a long prompt. +#[test] +fn a_turn_being_opened_stays_pinned_past_its_challenge_pin() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[4, 5], true)); + recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + let now = std::time::Instant::now(); + let past_window = now + CHALLENGE_PIN; + assert!(recorder.pinned_cells(past_window).is_empty()); + + let arrived = past_window - std::time::Duration::from_secs(2); + recorder.hold_for_opening("r1", arrived); + assert_eq!(cells(&recorder, past_window), vec![4, 5]); + assert_eq!( + recorder.next_pin_expiry(past_window), + Some(arrived + OPENING_PIN) + ); + // an opening that never ends gives the cells back + assert!(recorder.pinned_cells(arrived + OPENING_PIN).is_empty()); + // one that ends without rows to read leaves the challenge pin + recorder.end_opening("r1"); + assert!(recorder.pinned_cells(past_window).is_empty()); + assert_eq!(cells(&recorder, now), vec![4, 5]); + + // a challenge that comes after the pin ran out pins what still holds + // the turn's rows + recorder.memory_op(MemoryOp::SeqRm, -1, -1, -1, -1); + record(&recorder, ubatch(&[(2, 0)], &[5], true)); + recorder.hold_for_opening("r1", past_window); + assert_eq!(cells(&recorder, past_window), vec![4]); +} + +// A challenge may pick a position of the cached prefix. Its attention is +// checked like a position of the turn: the query is the one its mixing leaf +// holds, and every row it attends to is a cell of the prefix. +#[test] +fn an_attention_pick_in_the_prefix_reads_the_cells_below_it() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let prompt: Vec<(i32, i32)> = (0..70).map(|p| (3, p)).collect(); + let cells: Vec = (0..70).collect(); + record(&recorder, ubatch(&prompt, &cells, true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 70), (1, 71)], &[70, 71], true)); + let commitment = recorder.commit("r1", 1, TurnId::default(), 70..72).unwrap(); + let receipt = Receipt { + version: RECEIPT_VERSION, + receipt_id: "r1".into(), + model: "m".into(), + position_start: 70, + position_end: 72, + tokens: vec![1070, 1071], + generation_start: 71, + final_token: None, + stages: vec![commitment], + binding: None, + }; + let replayer = with_attention(FakeReplayer::for_stage(1), 2); + let pick = AttentionPick { + position: 40, + layer: 2, + head_draw: 0, + }; + let rows = open_and_check( + &recorder, + &replayer, + &receipt, + challenge(&[(2, &[40, 71])]), + pick, + ); + // the query attends to positions 0..=40, all cells of the prefix + let opened = &rows.stages[0].rows; + assert_eq!(opened.len(), 41); + assert!( + opened + .iter() + .all(|r| matches!(r.proof, RowProof::Prefix { .. })) + ); + // a row bound to other leaves than the prefix commits is refused + let mut forged = rows.clone(); + if let RowProof::Prefix { leaves, .. } = &mut forged.stages[0].rows[3].proof { + *leaves = hex::encode([9u8; 32]); + } + let layouts = BTreeMap::from([(2, layout(2))]); + assert!(verify_rows(&receipt, &layouts, &forged).is_err()); +} diff --git a/crates/skippy-receipts/src/recorder/budget_tests.rs b/crates/skippy-receipts/src/recorder/budget_tests.rs new file mode 100644 index 00000000..c7374e8f --- /dev/null +++ b/crates/skippy-receipts/src/recorder/budget_tests.rs @@ -0,0 +1,301 @@ +//! What the recorder keeps at its byte budgets: a turn a client can still +//! challenge keeps what opens it, and new work is refused first. + +use super::*; + +/// Commits a turn of three positions of `seq` on cells from `10 * seq`. +fn commit_turn(recorder: &Recorder, seq: i32, id: &str) -> anyhow::Result { + let columns: Vec<(i32, i32)> = (0..3).map(|p| (seq, p)).collect(); + let cells: Vec = (0..3).map(|p| (10 * seq + p) as u32).collect(); + record(recorder, ubatch(&columns, &cells, true)); + recorder.commit(id, seq, TurnId::default(), 0..3) +} + +// Past the window, a turn inside its challenge window keeps its record and +// the new turn gets no receipt; a turn past its window makes room. +#[test] +fn the_window_drops_only_turns_past_their_challenge_window() { + let measure = Recorder::new(1, STAGES[1].clone(), "cpu"); + commit_turn(&measure, 1, "one").unwrap(); + let turn = measure.lock().committed_bytes; + let recorder = + Recorder::new(1, STAGES[1].clone(), "cpu").with_window_bytes(2 * turn + turn / 2); + commit_turn(&recorder, 1, "victim").unwrap(); + commit_turn(&recorder, 2, "second").unwrap(); + let error = commit_turn(&recorder, 3, "third").unwrap_err(); + assert!( + format!("{error:#}").contains("gets no receipt"), + "{error:#}" + ); + assert!(recorder.holds_turn("victim") && recorder.holds_turn("second")); + assert!(!recorder.holds_turn("third")); + // the victim's window passed (here: nobody can challenge it any more) + recorder.release_pin("victim"); + commit_turn(&recorder, 4, "fourth").unwrap(); + assert!(!recorder.holds_turn("victim")); + assert!(recorder.holds_turn("second") && recorder.holds_turn("fourth")); +} + +// Past the lineage budget, the ubatch that wrote a prefix cell of a turn a +// client can still challenge is kept, and newer traffic loses its own: a +// later turn that reads it as its prefix gets no receipt. +#[test] +fn the_lineage_of_a_turn_inside_its_window_outlasts_the_budget() { + // a stage after the first keeps 4 bytes of input per token + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu").with_lineage_input_bytes(12); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r0", 1, TurnId::default(), 0..2).unwrap(); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + recorder.commit("r1", 1, TurnId::default(), 2..3).unwrap(); + // another request's prompt takes the budget past its end + record(&recorder, ubatch(&[(2, 0), (2, 1)], &[10, 11], true)); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[0, 2])]), &replayer) + .expect("the prefix position opens"); + + // the newer request's turn reads cells whose ubatch the stage dropped + recorder.memory_op(MemoryOp::SeqCp, 2, 3, -1, -1); + record(&recorder, ubatch(&[(3, 2)], &[12], true)); + let error = recorder + .commit("r3", 3, TurnId::default(), 2..3) + .unwrap_err(); + assert!(format!("{error:#}").contains("no longer held"), "{error:#}"); + + // once no client can challenge the turn, its lineage goes first + recorder.release_pin("r1"); + record(&recorder, ubatch(&[(4, 0), (4, 1)], &[20, 21], true)); + let error = recorder + .open(&challenge(&[(2, &[1, 2])]), &FakeReplayer::for_stage(1)) + .unwrap_err(); + assert!( + format!("{error:#}").contains("no longer holds"), + "{error:#}" + ); +} + +/// Whether the turn `id` is still pinned. +fn pinned(recorder: &Recorder, id: &str, now: Instant) -> bool { + let state = recorder.lock(); + turn(&state.committed, id).is_some_and(|turn| turn.pin.holds(now)) +} + +/// Makes the turn `id` as old as one no client challenged at once: it lingers. +fn linger(recorder: &Recorder, id: &str) { + let mut state = recorder.lock(); + let turn = turn_mut(&mut state.committed, id).expect("a committed turn"); + turn.pin.age(FIRM_PIN); +} + +// A turn nobody challenged at once is still held for a late challenge, and +// gives way when a new turn needs its room. A turn a client challenged does +// not, and when only such turns are left the new turn gets no receipt. +#[test] +fn a_lingering_turn_gives_way_to_a_new_turn_and_a_challenged_one_stays() { + let measure = Recorder::new(1, STAGES[1].clone(), "cpu"); + commit_turn(&measure, 1, "one").unwrap(); + let turn = measure.lock().committed_bytes; + let recorder = + Recorder::new(1, STAGES[1].clone(), "cpu").with_window_bytes(2 * turn + turn / 2); + commit_turn(&recorder, 1, "old").unwrap(); + commit_turn(&recorder, 2, "challenged").unwrap(); + linger(&recorder, "old"); + linger(&recorder, "challenged"); + let now = Instant::now(); + recorder.hold_for_opening("challenged", now); + assert!(pinned(&recorder, "old", now) && pinned(&recorder, "challenged", now)); + + commit_turn(&recorder, 3, "third").unwrap(); + assert!(!recorder.holds_turn("old"), "the lingering turn gave way"); + assert!(recorder.holds_turn("challenged") && recorder.holds_turn("third")); + let error = commit_turn(&recorder, 4, "fourth").unwrap_err(); + assert!( + format!("{error:#}").contains("gets no receipt"), + "{error:#}" + ); + assert!(recorder.holds_turn("challenged") && recorder.holds_turn("third")); +} + +// Lingering turns pin a quarter of a stream at most: past it the oldest +// lose their pin, and stay openable until a request writes their cells. +#[test] +fn lingering_turns_pin_a_quarter_of_a_stream_and_the_oldest_give_way() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a stream of 24 cells: lingering turns pin 6, and a turn has 3 + recorder.set_pin_budget(24); + let now = Instant::now(); + for (seq, id) in [(1, "l1"), (2, "l2"), (3, "l3")] { + commit_turn(&recorder, seq, id).unwrap(); + recorder.admit_pin(id, [seq as u8; 32], now).unwrap(); + } + // held firmly, every turn keeps its pin + assert_eq!(recorder.pinned_cells(now).len(), 9); + for id in ["l1", "l2", "l3"] { + linger(&recorder, id); + } + let now = Instant::now(); + assert_eq!(recorder.pinned_cells(now).len(), 6); + let pins: Vec = ["l1", "l2", "l3"] + .iter() + .map(|id| pinned(&recorder, id, now)) + .collect(); + assert_eq!(pins, [false, true, true]); + assert!(recorder.holds_turn("l1"), "still openable"); + // a new turn is pinned beside them: it is held firmly + commit_turn(&recorder, 4, "new").unwrap(); + recorder.admit_pin("new", [4; 32], now).unwrap(); + assert_eq!(recorder.pinned_cells(now).len(), 9); + assert!(pinned(&recorder, "new", now) && pinned(&recorder, "l2", now)); +} + +// A client that sends bound long turns cannot keep the cache pinned, and no +// turn loses its receipt for it: past its key's share the oldest pin of the +// key gives way, past the share of all keys the oldest pin of any key. +#[test] +fn past_a_share_the_oldest_pins_give_way_and_every_turn_keeps_its_receipt() { + const A: [u8; 32] = [1; 32]; + const B: [u8; 32] = [2; 32]; + const C: [u8; 32] = [3; 32]; + let now = Instant::now(); + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a stream of 12 cells: a key pins 6 at most, every key together 9 + recorder.set_pin_budget(12); + let bound = |seq: i32, id: &str, key: [u8; 32]| { + commit_turn(&recorder, seq, id).unwrap(); + recorder.admit_pin(id, key, now).unwrap(); + }; + let pins = + |ids: &[&str]| -> Vec { ids.iter().map(|id| pinned(&recorder, id, now)).collect() }; + bound(1, "a1", A); + bound(2, "a2", A); + assert_eq!(pins(&["a1", "a2"]), [true, true]); + // a third turn of the key: its oldest pin gives way + bound(3, "a3", A); + assert_eq!(pins(&["a1", "a2", "a3"]), [false, true, true]); + bound(4, "b1", B); + assert_eq!(recorder.pinned_cells(now).len(), 9); + // a turn of a third key: the oldest pin of any key gives way + bound(5, "c1", C); + assert_eq!(pins(&["a2", "a3", "b1", "c1"]), [false, true, true, true]); + assert_eq!(recorder.pinned_cells(now).len(), 9); + // every turn is still committed, so each has its receipt and opens + // until a ubatch writes its cells + assert!( + ["a1", "a2", "a3", "b1", "c1"] + .iter() + .all(|id| recorder.holds_turn(id)) + ); +} + +// A turn that a client has opened waits for its rows request, which will +// come; an unchallenged turn most likely has no challenge coming. So the +// unchallenged pins give way first, whatever their age. +#[test] +fn a_turn_that_waits_for_its_rows_request_keeps_its_pin_longest() { + const A: [u8; 32] = [1; 32]; + let now = Instant::now(); + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.set_pin_budget(12); + for (seq, id) in [(1, "opened"), (2, "idle")] { + commit_turn(&recorder, seq, id).unwrap(); + recorder.admit_pin(id, A, now).unwrap(); + } + { + let mut state = recorder.lock(); + let turn = turn_mut(&mut state.committed, "opened").unwrap(); + turn.pin.opened(now, true); + } + commit_turn(&recorder, 3, "new").unwrap(); + recorder.admit_pin("new", A, now).unwrap(); + assert!(pinned(&recorder, "opened", now) && pinned(&recorder, "new", now)); + assert!(!pinned(&recorder, "idle", now)); +} + +// A turn that is past a share by itself still gets its pin and its +// receipt: nothing else it could give way to. +#[test] +fn a_turn_past_a_share_alone_is_pinned_alone() { + const A: [u8; 32] = [1; 32]; + const B: [u8; 32] = [2; 32]; + let now = Instant::now(); + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a turn of 3 cells is past both shares of a stream of 3 + recorder.set_pin_budget(3); + commit_turn(&recorder, 1, "first").unwrap(); + recorder.admit_pin("first", A, now).unwrap(); + assert!(pinned(&recorder, "first", now)); + commit_turn(&recorder, 2, "second").unwrap(); + recorder.admit_pin("second", B, now).unwrap(); + assert!(pinned(&recorder, "second", now) && !pinned(&recorder, "first", now)); + assert!(recorder.holds_turn("first") && recorder.holds_turn("second")); +} + +// A turn's log counts against the window as its ubatches arrive: a long +// prefill that outgrows it is shed before it commits, and gets no receipt, +// rather than holding past the window until the commit's check. +#[test] +fn a_live_log_past_the_window_is_shed_before_its_commit() { + // a later stage's ubatch keeps its input rows: 4 KiB a token here + let wide = |columns: &[(i32, i32)], cells: &[u32], last: bool| { + let mut record = ubatch(columns, cells, last); + record.input = Some(StageInput { + rows: vec![7; columns.len() * 4096], + row_bytes: 4096, + ggml_type: 0, + }); + record + }; + let measure = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&measure, wide(&[(1, 0)], &[0], true)); + measure.commit("one", 1, TurnId::default(), 0..1).unwrap(); + let one = measure.lock().committed_bytes; + let window = one + 2 * 3 * 4096; + + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu").with_window_bytes(window); + for chunk in 0..4 { + let columns: Vec<(i32, i32)> = (0..3).map(|p| (1, 3 * chunk + p)).collect(); + let cells: Vec = (0..3).map(|p| (3 * chunk + p) as u32).collect(); + record(&recorder, wide(&columns, &cells, chunk == 3)); + let held = recorder.lock().held_bytes(); + assert!(held <= window, "ubatch {chunk}: {held} of {window}"); + } + { + // a shed log keeps nothing per position, also for the ubatches + // after it was shed, and its prefix only as a stand-in + let state = recorder.lock(); + let log = &state.seqs[&1].live; + assert!(log.shed); + assert!(log.leaves.is_empty() && log.events.is_empty()); + assert!(matches!(log.prefix, Some(Err(_)))); + assert_eq!(log.live_bytes(), 0); + } + let error = recorder + .commit("long", 1, TurnId::default(), 0..12) + .unwrap_err(); + assert!(format!("{error:#}").contains("outgrew"), "{error:#}"); + + // the sequence's next turn records and commits again + recorder.begin_turn(1, TurnId(1)); + record(&recorder, wide(&[(1, 12)], &[12], true)); + recorder.commit("next", 1, TurnId(1), 12..13).unwrap(); + assert!(recorder.holds_turn("next")); +} + +// The window counts the hashes a live log keeps per position and its +// prefix, not only its ubatches: a turn of decode tokens, whose ubatches +// carry no input rows, still counts what it holds. +#[test] +fn a_live_log_counts_its_positions_and_prefix() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + let state = recorder.lock(); + let log = &state.seqs[&1].live; + let positions: usize = log.leaves.values().map(leaves::PositionLeaves::bytes).sum(); + assert_eq!(log.leaves.len(), 2); + assert!(positions > 0); + assert_eq!( + log.live_bytes(), + log.event_bytes + positions + log.prefix_bytes() + ); + assert_eq!(log.live_bytes(), log.bytes()); +} diff --git a/crates/skippy-receipts/src/recorder/cannot_open_tests.rs b/crates/skippy-receipts/src/recorder/cannot_open_tests.rs new file mode 100644 index 00000000..cc09c5fa --- /dev/null +++ b/crates/skippy-receipts/src/recorder/cannot_open_tests.rs @@ -0,0 +1,241 @@ +//! A stage says so, with a reason, when it can no longer open a turn it +//! committed, and loses a turn's cells only to what can have changed them. + +use super::*; + +/// The [`CannotOpen`] an opening failed with. +fn cannot_open(error: &anyhow::Error) -> &CannotOpen { + error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a cannot-open answer: {error:#}")) +} + +/// Sequences 1 and 2 each commit a turn of two positions after a prefix of +/// three. Sequence 1 goes on holding its cells; sequence 2 ends, so its +/// cells are free and keep their rows. Returns the seed of each turn's +/// replay. +fn two_turns(recorder: &Recorder) -> [ReplaySeed; 2] { + [1, 2].map(|seq| { + let cells = |positions: std::ops::Range| -> Vec { + positions.map(|p| (seq * 10 + p) as u32).collect() + }; + let columns = |positions: std::ops::Range| -> Vec<(i32, i32)> { + positions.map(|p| (seq, p)).collect() + }; + record(recorder, ubatch(&columns(0..3), &cells(0..3), true)); + let earlier = format!("earlier-{seq}"); + recorder + .commit(&earlier, seq, TurnId::default(), 0..3) + .unwrap(); + record(recorder, ubatch(&columns(3..5), &cells(3..5), true)); + let id = format!("r{seq}"); + recorder.commit(&id, seq, TurnId::default(), 3..5).unwrap(); + if seq == 2 { + recorder.memory_op(MemoryOp::SeqRm, seq, -1, -1, -1); + } + let replayer = FakeReplayer::for_stage(1); + let mut challenge = challenge(&[(2, &[4])]); + challenge.receipt_id = id; + recorder.open(&challenge, &replayer).unwrap(); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + recorder.check_seed(&seed).unwrap(); + seed + }) +} + +// A ubatch the recorder could not follow may have written any cell no +// sequence held, and no other: a turn whose cells are still held stays +// openable, and one whose cells were free is refused with the reason. +#[test] +fn an_unreceiptable_ubatch_costs_only_the_cells_no_sequence_holds() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let [held, freed] = two_turns(&recorder); + recorder.unreceiptable("two lanes in one recurrent ubatch"); + recorder.check_seed(&held).unwrap(); + let error = recorder.check_seed(&freed).unwrap_err(); + let cannot = cannot_open(&error); + assert_eq!(cannot.reason, CannotOpenReason::CellsUnknown); + assert_eq!(cannot.stage_index, 1); +} + +// An image request beside a receipted turn: the native recorder reports a +// ubatch of embeddings it cannot receipt, and names neither its sequences +// nor its cells. Taken as the recorder losing track of the stage, it costs +// every live turn its receipt; taken as one ubatch, it costs only the turns +// whose logs show it computed something they lack. +#[test] +fn an_unrecorded_ubatch_costs_only_the_turns_it_computed() { + let lost = Recorder::new(1, STAGES[1].clone(), "cpu"); + record( + &lost, + ubatch(&[(1, 0), (1, 1), (1, 2)], &[10, 11, 12], true), + ); + lost.unreceiptable("a ubatch of embeddings cannot be receipted"); + record(&lost, ubatch(&[(1, 3)], &[13], true)); + let error = lost.commit("r1", 1, TurnId::default(), 0..4).unwrap_err(); + assert!( + format!("{error:#}").contains("cannot be replayed"), + "{error:#}" + ); + + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record( + &recorder, + ubatch(&[(1, 0), (1, 1), (1, 2)], &[10, 11, 12], true), + ); + record( + &recorder, + ubatch(&[(3, 0), (3, 1), (3, 2)], &[30, 31, 32], true), + ); + // sequence 3's image at positions 3 and 4 + recorder.unrecorded_ubatch("a ubatch of embeddings cannot be receipted"); + record(&recorder, ubatch(&[(1, 3), (3, 5)], &[13, 35], true)); + // sequence 1 recorded every position of its turn: it keeps its receipt + recorder.commit("r1", 1, TurnId::default(), 0..4).unwrap(); + // sequence 3 lacks what the ubatch computed, whichever positions it names + for positions in [0..6, 5..6] { + let error = recorder + .commit("r3", 3, TurnId::default(), positions.clone()) + .unwrap_err(); + assert!(!recorder.holds_turn("r3"), "{positions:?}: {error:#}"); + } +} + +// The cache writes a free pinned cell only when nothing else fits, so a +// ubatch the recorder could not record leaves a pinned turn openable once +// its rows are read and match; a turn that is not pinned, or whose rows no +// longer match, is answered with the reason. +#[test] +fn an_unrecorded_ubatch_leaves_a_pinned_turn_openable() { + let freed_turn = |recorder: &Recorder| { + record( + recorder, + ubatch(&[(2, 0), (2, 1), (2, 2)], &[20, 21, 22], true), + ); + recorder + .commit("earlier", 2, TurnId::default(), 0..3) + .unwrap(); + record(recorder, ubatch(&[(2, 3), (2, 4)], &[23, 24], true)); + recorder.commit("r2", 2, TurnId::default(), 3..5).unwrap(); + recorder.memory_op(MemoryOp::SeqRm, 2, -1, -1, -1); + let mut challenge = challenge(&[(2, &[4])]); + challenge.receipt_id = "r2".into(); + challenge + }; + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let challenge = freed_turn(&recorder); + assert_eq!(recorder.pinned_cells(Instant::now()).len(), 5); + recorder.unrecorded_ubatch("a ubatch of embeddings cannot be receipted"); + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge, &replayer).unwrap(); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + recorder.check_seed(&seed).unwrap(); + + // rows another write left in a pinned cell + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let challenge = freed_turn(&recorder); + recorder.pinned_cells(Instant::now()); + recorder.unrecorded_ubatch("a ubatch of embeddings cannot be receipted"); + let replayer = FakeReplayer { + stale_rows: true, + ..FakeReplayer::for_stage(1) + }; + let error = recorder.open(&challenge, &replayer).unwrap_err(); + let cannot = cannot_open(&error); + assert_eq!(cannot.reason, CannotOpenReason::CellsOverwritten); + assert_eq!(cannot.receipt_id, "r2"); + + // nothing pinned: the free cells are forgotten + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let challenge = freed_turn(&recorder); + recorder.unrecorded_ubatch("a ubatch of embeddings cannot be receipted"); + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge, &replayer).unwrap(); + // the stage checks the seed with the stage idle, before it copies it + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + let error = recorder.check_seed(&seed).unwrap_err(); + assert_eq!(cannot_open(&error).reason, CannotOpenReason::CellsUnknown); +} + +// What happens to one sequence's cells leaves another's turn openable. +#[test] +fn a_change_of_one_sequence_leaves_the_others_openable() { + for op in [MemoryOp::SeqShift, MemoryOp::StateRead] { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let [held, _] = two_turns(&recorder); + recorder.memory_op(op, 5, -1, -1, -1); + recorder.check_seed(&held).unwrap(); + recorder.memory_op(op, 1, -1, 0, -1); + let error = recorder.check_seed(&held).unwrap_err(); + assert_eq!(cannot_open(&error).reason, CannotOpenReason::CellsUnknown); + } + // a shift of sequence 1 does not reach the free cells of sequence 2's turn + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let [_, freed] = two_turns(&recorder); + recorder.memory_op(MemoryOp::SeqShift, 1, -1, 0, -1); + recorder.check_seed(&freed).unwrap(); +} + +// A cell a later request wrote, a turn that left the window and a dropped +// recurrent state are each answered as such. +#[test] +fn an_opening_names_why_the_stage_cannot_make_it() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let [_, freed] = two_turns(&recorder); + record(&recorder, ubatch(&[(9, 0)], &[21], true)); + let error = recorder.check_seed(&freed).unwrap_err(); + assert_eq!( + cannot_open(&error).reason, + CannotOpenReason::CellsOverwritten + ); + + let replayer = FakeReplayer::for_stage(1); + let mut gone = challenge(&[(2, &[4])]); + gone.receipt_id = "never-committed".into(); + let error = recorder.open(&gone, &replayer).unwrap_err(); + let cannot = cannot_open(&error); + assert_eq!(cannot.reason, CannotOpenReason::Expired); + assert_eq!(cannot.receipt_id, "never-committed"); + assert!(recorder.check_challenge(&gone).is_err()); + assert!(!recorder.holds_turn("never-committed") && recorder.holds_turn("r1")); +} + +// A stage checks a challenge's size against what a draw makes before it +// replays anything, also when it holds no receipt to check it against. +#[test] +fn a_stage_refuses_a_challenge_no_draw_makes() { + let node = Node::two_lane_turn(); + node.commit(7, 0..4, 3); + let recorder = &node.stages[1]; + recorder + .check_challenge(&challenge(&[(2, &[0, 3]), (3, &[1])])) + .unwrap(); + let every_layer: Vec<(u32, &[u32])> = (0..8).map(|l| (l, &[0u32][..])).collect(); + let mut twice = challenge(&[(2, &[1])]); + twice.attention = vec![ + crate::attention::opening::AttentionPick { + position: 1, + layer: 2, + head_draw: 0, + }; + 2 + ]; + let mut heads = challenge(&[(2, &[1])]); + heads.head = vec![0, 1, 2, 3, 4]; + for refused in [ + challenge(&every_layer), + challenge(&[(2, &[0, 1, 2, 3, 4])]), + challenge(&[(2, &[])]), + challenge(&[(2, &[2, 1])]), + challenge(&[(2, &[4])]), + challenge(&[(3, &[1]), (2, &[1])]), + challenge(&[(9, &[1])]), + twice, + heads, + ] { + assert!( + recorder.check_challenge(&refused).is_err(), + "admitted {refused:?}" + ); + } +} diff --git a/crates/skippy-receipts/src/recorder/cells.rs b/crates/skippy-receipts/src/recorder/cells.rs new file mode 100644 index 00000000..4ecef59f --- /dev/null +++ b/crates/skippy-receipts/src/recorder/cells.rs @@ -0,0 +1,790 @@ +//! A mirror of the stage's KV cells: which positions of which sequences each +//! cell holds, what the stage committed when it wrote the cell, and the +//! ubatch that wrote it. +//! +//! A turn attends to cells written before it: by the sequence's earlier turns, +//! or by another request whose cached prefix the sequence shares (`seq_cp` +//! shares cells without copying them). A replay of the turn starts from a +//! copy of those cells instead of replaying how they were written, and the +//! receipt binds them by their digests ([`prefix_root`]). The mirror follows +//! the native cache from the ubatches that write cells and the memory events +//! that move them, so it knows which cells a sequence holds, and whether they +//! still hold what the turn attended to when it is opened. +//! +//! A client may challenge a position of that prefix. The stage then replays +//! the one ubatch that wrote the position, from a copy of the cells below +//! it. So every cell keeps its lineage: the leaves the stage committed for +//! its position, and the recorded ubatch ([`Lineage`]). The copy equals what +//! the ubatch read only when the cells below the ubatch are still the ones +//! it ran on. The mirror tracks that with a stamp per sequence +//! ([`lineage`](super::lineage)): a ubatch that appends to a sequence notes +//! the stamp it found and leaves a new one, and [`CellMirror::prefix`] +//! follows the stamps from position 0. A sequence the mirror cannot follow +//! (a shift, a state load, a write that is not an append, cells taken from +//! two sources) has no prefix until it is emptied. +//! +//! A cache that is not unified keeps a stream of cells per sequence, each +//! numbering its own cells from 0. There `seq_cp` copies the source's whole +//! stream into the destination's, rows and all. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; + +use anyhow::{Context, Result, bail, ensure}; + +use super::UbatchRecord; +use super::event_log::{removed, removes_all}; +use super::lineage::{EMPTY, Runs, Shape, Stamp}; +use crate::commitment::{self, Hash, MerkleTree}; + +/// A KV-cache operation the stage reports (`skippy_receipt_memory_op`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MemoryOp { + Clear, + SeqRm, + SeqCp, + SeqKeep, + /// `seq_add` or `seq_div`. + SeqShift, + StateRead, + Compact, +} + +impl MemoryOp { + pub fn from_code(code: i32) -> Option { + Some(match code { + 0 => Self::Clear, + 1 => Self::SeqRm, + 2 => Self::SeqCp, + 3 => Self::SeqKeep, + 4 => Self::SeqShift, + 5 => Self::StateRead, + 6 => Self::Compact, + _ => return None, + }) + } +} + +/// How the stage's KV cache lays out its cells. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum KvStreams { + /// One stream that every sequence shares. + #[default] + Shared, + /// A stream per sequence, numbered as the sequence. + PerSequence, +} + +impl KvStreams { + /// The stream that holds the cells of `seq`. + pub fn of(self, seq: i32) -> u32 { + match self { + Self::Shared => 0, + Self::PerSequence => u32::try_from(seq).unwrap_or(0), + } + } +} + +/// A cell of the stage's KV cache: its stream and its index there. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct KvCell { + pub stream: u32, + pub cell: u32, +} + +/// One cell a sequence holds below a turn's first position. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PrefixCell { + pub pos: i32, + /// The stream that holds the cell, which a turn's cells share, and the + /// cell's index in it. The receipt binds the index alone. + pub stream: u32, + pub cell: u32, + /// Digest of the leaves the stage committed when it computed the + /// position, which bind the rows it stored in the cell + /// ([`crate::commitment::cell_digest`]). + pub digest: Hash, +} + +/// What a stage committed in one column of a ubatch, kept with the cell +/// the column wrote. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ColumnLeaves { + /// The digest of the rows the stage stored in the cell. + pub cell: Hash, + /// Every leaf the stage committed at the position, in slot order. + pub leaves: Arc<[Hash]>, + /// The digest of the leaves ([`commitment::position_digest`]). + pub position: Hash, +} + +/// The cells a turn attended to below its first position, from position 0: +/// what its replay starts from and what its receipt commits. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct TurnPrefix { + pub cells: Vec, + /// By position, the digest of the leaves the stage committed there. + pub positions: Vec, + /// By position, the token the stage computed there. Meaningful on the + /// stage that holds layer 0. + pub tokens: Vec, +} + +impl TurnPrefix { + pub fn len(&self) -> usize { + self.cells.len() + } + + pub fn is_empty(&self) -> bool { + self.cells.is_empty() + } + + /// Bytes the prefix holds. + pub fn bytes(&self) -> usize { + self.cells.len() * (size_of::() + size_of::() + size_of::()) + } +} + +/// How a prefix position was computed: the recorded ubatch that wrote its +/// cell, and the leaves the stage committed for it then. +#[derive(Clone, Debug)] +pub(crate) struct Lineage { + pub record: Arc, + /// The column of the ubatch that computed the position. + pub col: usize, + /// The first position the ubatch computed for the column's sequence. + pub first: i32, + pub leaves: Arc<[Hash]>, +} + +impl Lineage { + /// The sequence the ubatch computed the position for. + pub fn writer(&self) -> i32 { + self.record.seq[self.col] + } +} + +#[derive(Clone, Debug)] +struct Cell { + pos: i32, + /// Empty once every sequence freed the cell: it keeps its rows until a + /// ubatch writes it again, so a turn that used it can still open them. + seqs: BTreeSet, + /// `None` when the recorder could not hash what the stage computed. + committed: Option, + /// The run that wrote the cell ([`Runs`]), and its column there. + run: u64, + col: u32, + /// The cell was free and pinned when a write the recorder did not see + /// happened. The cache writes a pinned cell only when nothing else + /// fits, so it most likely still holds its rows, but only reading + /// them tells ([`CellRecord::Exposed`]). + exposed: bool, +} + +impl Cell { + fn digest(&self) -> Option { + self.committed.as_ref().map(|committed| committed.cell) + } +} + +/// A cell: its stream and its index there. +type CellKey = (u32, u32); + +#[derive(Default)] +pub(crate) struct CellMirror { + streams: KvStreams, + cells: HashMap, + /// By sequence, its cells (in its stream) by position. + by_seq: HashMap>, + /// The ubatches that wrote the cells. + runs: Runs, + /// What the mirror knows of each sequence's cells as a whole. A + /// sequence without an entry holds no cells, unless `unknown`. + shapes: HashMap, + /// A sequence without an entry may hold cells the mirror does not know. + unknown: bool, + /// Runs whose ubatch the input budget keeps: the lineage of a turn a + /// client can still challenge ([`Self::protect_runs`]). + protected_runs: BTreeSet, +} + +/// What the mirror knows of a cell a turn read or wrote. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CellRecord { + /// It still holds what the turn read or wrote. + Held, + /// A later ubatch wrote it. + Overwritten, + /// The mirror no longer knows what it holds. + Unknown, + /// It holds what the turn read, but the stage dropped the ubatch that + /// computed it, so it cannot be replayed. + Dropped, + /// The mirror saw nothing overwrite it, but a write the recorder did + /// not see happened while it was free and pinned: its rows must be + /// checked against its digest before an opening reads it + /// ([`super::Recorder::verify_exposed`]). + Exposed, +} + +impl CellRecord { + /// Whether the mirror saw nothing overwrite the cell. + fn unseen_overwrite(self) -> bool { + matches!(self, Self::Held | Self::Exposed) + } +} + +impl CellMirror { + pub fn streams(&self) -> KvStreams { + self.streams + } + + /// Sets how the cache lays out its cells; the mirror forgets every cell. + pub fn set_streams(&mut self, streams: KvStreams) { + self.forget_all(false); + self.streams = streams; + } + + /// Sets the bytes of later-stage input rows the mirror keeps for the + /// lineage of its cells. + pub fn set_input_budget(&mut self, bytes: usize) { + self.runs.set_input_budget(bytes); + } + + /// Keeps the ubatches of `runs` past the input budget, in place of those + /// kept before. + pub fn protect_runs(&mut self, runs: BTreeSet) { + self.protected_runs = runs; + } + + /// The runs that wrote the cells of `prefix`: what a replay of one of + /// its positions needs. + pub fn lineage_runs(&self, prefix: &TurnPrefix) -> Vec { + let runs: BTreeSet = prefix + .cells + .iter() + .filter_map(|cell| Some(self.cells.get(&(cell.stream, cell.cell))?.run)) + .collect(); + runs.into_iter().collect() + } + + fn shape(&self, seq: i32) -> Shape { + self.shapes.get(&seq).copied().unwrap_or(Shape { + stamp: EMPTY, + replayable: !self.unknown, + }) + } + + fn held(&self, seq: i32) -> usize { + self.by_seq.get(&seq).map_or(0, BTreeMap::len) + } + + /// One past the last position `seq` holds. + fn end(&self, seq: i32) -> i32 { + self.by_seq + .get(&seq) + .and_then(|positions| positions.keys().next_back()) + .map_or(0, |last| last + 1) + } + + /// The stamp of the cells `seq` holds below `end`, when a replay can + /// follow the sequence and it holds them all. + fn stamp_below(&self, seq: i32, end: i32) -> Option { + if !self.shape(seq).replayable { + return None; + } + if end <= 0 { + return Some(EMPTY); + } + let cell = *self.by_seq.get(&seq)?.get(&(end - 1))?; + let cell = self.cells.get(&(self.streams.of(seq), cell))?; + self.runs.stamp_through(cell.run, end - 1) + } + + /// A ubatch wrote each column's position into its cell; whatever the + /// cells held before is gone. `committed` holds what the stage committed + /// in each column, `None` where the recorder could not hash it. + pub fn write_ubatch( + &mut self, + record: &Arc, + committed: Vec>, + ) { + let mut columns: BTreeMap> = BTreeMap::new(); + for (col, &seq) in record.seq.iter().enumerate() { + self.free((self.streams.of(seq), record.cell[col])); + columns.entry(seq).or_default().push(col); + } + let mut committed = committed.into_iter().map(Some).collect::>(); + for (seq, cols) in columns { + let first = record.pos[cols[0]]; + let consecutive = cols + .iter() + .zip(first..) + .all(|(&col, pos)| record.pos[col] == pos); + let shape = self.shape(seq); + // an append continues what the sequence holds; any other write + // leaves cells a replay of one ubatch cannot start from + let appends = + shape.replayable && consecutive && usize::try_from(first) == Ok(self.held(seq)); + let last = first + i32::try_from(cols.len()).unwrap_or(i32::MAX) - 1; + let (run, after) = self.runs.begin( + record, + cols.len(), + first..last + 1, + appends.then_some(shape.stamp), + ); + for col in cols { + let cell = Cell { + pos: record.pos[col], + seqs: BTreeSet::from([seq]), + committed: committed.get_mut(col).and_then(Option::take).flatten(), + run, + col: u32::try_from(col).unwrap_or(u32::MAX), + exposed: false, + }; + self.by_seq + .entry(seq) + .or_default() + .insert(cell.pos, record.cell[col]); + self.runs.hold(run); + self.cells + .insert((self.streams.of(seq), record.cell[col]), cell); + } + self.shapes.insert( + seq, + Shape { + stamp: after, + replayable: appends, + }, + ); + } + self.runs.enforce_budget(&self.protected_runs); + } + + /// Forgets the cell at `key`. A sequence that still held it loses a + /// position a replay cannot account for. + fn free(&mut self, key: CellKey) { + if let Some(old) = self.cells.remove(&key) { + for seq in old.seqs { + self.unlink(seq, old.pos, key.1); + self.shapes.insert(seq, Shape::UNREPLAYABLE); + } + self.runs.release(old.run); + } + } + + fn unlink(&mut self, seq: i32, pos: i32, cell: u32) { + if let Some(positions) = self.by_seq.get_mut(&seq) { + if positions.get(&pos) == Some(&cell) { + positions.remove(&pos); + } + if positions.is_empty() { + self.by_seq.remove(&seq); + } + } + } + + /// Forgets every cell. Afterwards a sequence holds nothing, or, with + /// `unknown`, cells the mirror does not know. + fn forget_all(&mut self, unknown: bool) { + self.cells.clear(); + self.by_seq.clear(); + self.runs.clear(); + self.shapes.clear(); + self.unknown = unknown; + } + + /// `seq` (every sequence if negative) lost its cells in `[p0, p1)`. The + /// cache frees a cell without changing its rows. + pub fn seq_rm(&mut self, seq: i32, p0: i32, p1: i32) { + let range = removed(p0, p1); + let seqs: Vec = if seq < 0 { + self.by_seq.keys().copied().collect() + } else { + vec![seq] + }; + if seq < 0 && removes_all(p0, p1) { + // every sequence is empty, also one the mirror did not know + self.shapes.clear(); + self.unknown = false; + } + for s in seqs { + let end = self.end(s); + let known = self.shape(s).replayable; + let shape = if removes_all(p0, p1) || (known && range.start <= 0 && range.end >= end) { + Some(Shape { + stamp: EMPTY, + replayable: true, + }) + } else if range.start >= end { + None + } else if range.end >= end { + // the tail went: what is left is what the sequence held + // when it reached the position below the cut + Some( + self.stamp_below(s, range.start) + .map_or(Shape::UNREPLAYABLE, |stamp| Shape { + stamp, + replayable: true, + }), + ) + } else { + Some(Shape::UNREPLAYABLE) + }; + if let Some(shape) = shape { + self.shapes.insert(s, shape); + } + let Some(positions) = self.by_seq.get(&s) else { + continue; + }; + let removed: Vec<(i32, u32)> = positions + .range(range.clone()) + .map(|(&p, &c)| (p, c)) + .collect(); + let stream = self.streams.of(s); + for (pos, cell) in removed { + self.unlink(s, pos, cell); + if let Some(entry) = self.cells.get_mut(&(stream, cell)) { + entry.seqs.remove(&s); + } + } + } + } + + /// The cells of `src` in `[p0, p1)` are now also cells of `dst`. Across + /// streams, the destination's stream becomes a copy of the source's. + pub fn seq_cp(&mut self, src: i32, dst: i32, p0: i32, p1: i32) { + if src == dst { + return; + } + let (from, to) = (self.streams.of(src), self.streams.of(dst)); + if from != to { + self.copy_stream(src, dst); + return; + } + let range = removed(p0, p1); + // an empty destination that takes the source's cells from 0 holds + // what the source held when it reached the last of them + let fresh = self.held(dst) == 0 && self.shape(dst).replayable && range.start == 0; + let stamp = fresh + .then(|| self.stamp_below(src, range.end.min(self.end(src)))) + .flatten(); + let shared: Vec<(i32, u32)> = self + .by_seq + .get(&src) + .map(|positions| positions.range(range).map(|(&p, &c)| (p, c)).collect()) + .unwrap_or_default(); + for (pos, cell) in shared { + if let Some(entry) = self.cells.get_mut(&(from, cell)) { + entry.seqs.insert(dst); + } + self.by_seq.entry(dst).or_default().insert(pos, cell); + } + self.shapes.insert( + dst, + stamp.map_or(Shape::UNREPLAYABLE, |stamp| Shape { + stamp, + replayable: true, + }), + ); + } + + /// The cache copies every row of the source's stream into the + /// destination's, which then holds `dst` where the source held `src`. + fn copy_stream(&mut self, src: i32, dst: i32) { + let (from, to) = (self.streams.of(src), self.streams.of(dst)); + let shape = self.shape(src); + let replaced: Vec = self.cells.keys().copied().filter(|k| k.0 == to).collect(); + for key in replaced { + self.free(key); + } + let copied: Vec<(u32, Cell)> = self + .cells + .iter() + .filter(|(k, _)| k.0 == from) + .map(|(k, c)| { + let seqs = if c.seqs.contains(&src) { + BTreeSet::from([dst]) + } else { + BTreeSet::new() + }; + (k.1, Cell { seqs, ..c.clone() }) + }) + .collect(); + for (cell, entry) in copied { + if entry.seqs.contains(&dst) { + self.by_seq.entry(dst).or_default().insert(entry.pos, cell); + } + self.runs.hold(entry.run); + self.cells.insert((to, cell), entry); + } + self.shapes.insert(dst, shape); + } + + /// Every sequence but `seq` lost its cells. + pub fn seq_keep(&mut self, seq: i32) { + let others: Vec = self.by_seq.keys().copied().filter(|&s| s != seq).collect(); + for other in others { + self.seq_rm(other, -1, -1); + } + } + + /// The positions of the cells `seq` holds in `[p0, p1)` changed, and the + /// cache rewrites their rows to match: every sequence that shares one + /// of those cells loses it. No other cell changes. + fn forget_shifted(&mut self, seq: i32, p0: i32, p1: i32) { + self.shapes.insert(seq, Shape::UNREPLAYABLE); + let Some(positions) = self.by_seq.get(&seq) else { + return; + }; + let stream = self.streams.of(seq); + let shifted: Vec = positions.range(removed(p0, p1)).map(|(_, &c)| c).collect(); + for cell in shifted { + self.free((stream, cell)); + } + } + + /// Something the recorder did not see wrote cells. The cache places a + /// write in cells no sequence holds, so a cell some sequence still + /// holds keeps its record. (Under a sliding attention window the cache + /// may also take a cell whose position its sequence no longer attends + /// to; no opening reads such a cell.) + /// + /// Among the free cells, the cache takes one of `pinned` only when the + /// write fits nowhere else. So a free cell that is not pinned is + /// forgotten, and a pinned one keeps its record, marked + /// [`CellRecord::Exposed`] until its rows are checked. + /// + /// The write gave some sequence positions the mirror has no cell for. + /// A prefix over them fails for the missing cell, and the next ubatch + /// the recorder sees on that sequence is not an append. + pub fn unseen_write(&mut self, pinned: &BTreeSet) { + let mut freed = Vec::new(); + for (&key, cell) in &mut self.cells { + if !cell.seqs.is_empty() { + continue; + } + let (stream, cell_index) = key; + if pinned.contains(&KvCell { + stream, + cell: cell_index, + }) { + cell.exposed = true; + } else { + freed.push(key); + } + } + for key in freed { + self.free(key); + } + } + + /// The rows of `cell` were read and match its digest: it holds what the + /// turn read or wrote. + pub fn clear_exposed(&mut self, cell: &PrefixCell) { + if let Some(held) = self.cells.get_mut(&(cell.stream, cell.cell)) + && held.pos == cell.pos + && held.digest() == Some(cell.digest) + { + held.exposed = false; + } + } + + /// Follows a KV-cache operation (`skippy_receipt_memory_op`), forgetting + /// only the cells the operation can have changed: + /// + /// - a shift of one sequence changes the cells that sequence holds in + /// the shifted span; + /// - a state load into one sequence replaces that sequence's cells with + /// rows written to cells no sequence held; + /// - a clear may zero every row, compaction moves cells, and a shift or + /// state load that names no sequence touches them all, so each of + /// these does invalidate the whole cache. + pub fn memory_op( + &mut self, + op: MemoryOp, + (seq, seq_dst): (i32, i32), + (p0, p1): (i32, i32), + pinned: &BTreeSet, + ) { + match op { + MemoryOp::SeqRm => self.seq_rm(seq, p0, p1), + MemoryOp::SeqCp => self.seq_cp(seq, seq_dst, p0, p1), + MemoryOp::SeqKeep => self.seq_keep(seq), + MemoryOp::SeqShift if seq >= 0 => self.forget_shifted(seq, p0, p1), + MemoryOp::StateRead if seq >= 0 => { + self.seq_rm(seq, -1, -1); + self.unseen_write(pinned); + // the sequence holds the loaded rows, which nothing recorded + self.shapes.insert(seq, Shape::UNREPLAYABLE); + } + MemoryOp::Clear => self.forget_all(false), + MemoryOp::SeqShift | MemoryOp::StateRead | MemoryOp::Compact => self.forget_all(true), + } + } + + /// The cells `seq` holds below `end`, which must be every position from + /// 0, each with what the stage committed for it and the ubatch that + /// wrote it, and each written on top of the cells below it. + pub fn prefix(&self, seq: i32, end: u32) -> Result { + let end = i32::try_from(end)?; + let mut prefix = TurnPrefix::default(); + if end == 0 { + return Ok(prefix); + } + ensure!( + self.shape(seq).replayable, + "the sequence's cells changed in a way a replay of one ubatch cannot follow" + ); + let stream = self.streams.of(seq); + let positions = self.by_seq.get(&seq); + // the run and position of the cell below the one in hand + let mut below: Option<(u64, i32)> = None; + for pos in 0..end { + let Some(&cell) = positions.and_then(|p| p.get(&pos)) else { + bail!("the sequence holds no recorded cell at position {pos}"); + }; + let held = self.cells.get(&(stream, cell)); + let Some((held, committed)) = held.and_then(|c| Some((c, c.committed.as_ref()?))) + else { + bail!("the rows stored at position {pos} were not recorded"); + }; + let run = self + .runs + .get(held.run) + .with_context(|| format!("nothing recorded the ubatch of position {pos}"))?; + let Some(record) = &run.record else { + bail!("the ubatch that wrote position {pos} is no longer held"); + }; + let found = match below { + None => Some(EMPTY), + Some((run, at)) => self.runs.stamp_through(run, at), + }; + let follows = if pos == run.positions.start { + run.before.is_some() && run.before == found + } else { + below.is_some_and(|(run, _)| run == held.run) + }; + ensure!( + follows && record.pos.get(held.col as usize) == Some(&pos), + "position {pos} was not computed on top of the cells below it" + ); + below = Some((held.run, pos)); + prefix.cells.push(PrefixCell { + pos, + stream, + cell, + digest: committed.cell, + }); + prefix.positions.push(committed.position); + prefix.tokens.push(record.token[held.col as usize]); + } + Ok(prefix) + } + + /// Whether nothing the mirror saw overwrote `cell` since the prefix was + /// taken: it holds the rows, or may and is to be checked. + pub fn holds(&self, cell: &PrefixCell) -> bool { + self.record(cell).unseen_overwrite() + } + + /// What the mirror knows of `cell` since a turn read or wrote it. + pub fn record(&self, cell: &PrefixCell) -> CellRecord { + match self.cells.get(&(cell.stream, cell.cell)) { + Some(c) if c.pos == cell.pos && c.digest() == Some(cell.digest) => { + if c.exposed { + CellRecord::Exposed + } else { + CellRecord::Held + } + } + Some(_) => CellRecord::Overwritten, + None => CellRecord::Unknown, + } + } + + /// Fails unless every cell of `prefix` still holds what it held when + /// the prefix was taken, with the ubatch that computed it. + pub fn check_lineage(&self, prefix: &TurnPrefix) -> Result<()> { + for (cell, position) in prefix.cells.iter().zip(&prefix.positions) { + let run = match self.cells.get(&(cell.stream, cell.cell)) { + Some(held) + if held.pos == cell.pos + && held.committed.as_ref().is_some_and(|committed| { + committed.cell == cell.digest && &committed.position == position + }) => + { + self.runs.get(held.run) + } + _ => bail!( + "the cell of position {} of the cached prefix was written again", + cell.pos + ), + }; + ensure!( + run.is_some_and(|run| run.record.is_some()), + "the ubatch that wrote position {} of the cached prefix is no longer held", + cell.pos + ); + } + Ok(()) + } + + /// How `cell`, a prefix cell whose leaves hash to `position`, was + /// computed. The error says what the mirror knows of a cell that no + /// longer holds it, or whose ubatch the stage dropped. + pub fn lineage( + &self, + cell: &PrefixCell, + position: &Hash, + ) -> std::result::Result { + // an exposed cell is checked before the seed that copies it + let held = match self.record(cell) { + CellRecord::Held | CellRecord::Exposed => &self.cells[&(cell.stream, cell.cell)], + record => return Err(record), + }; + let committed = held + .committed + .as_ref() + .filter(|committed| &committed.position == position) + .ok_or(CellRecord::Overwritten)?; + let run = self.runs.get(held.run).ok_or(CellRecord::Unknown)?; + Ok(Lineage { + record: run.record.clone().ok_or(CellRecord::Dropped)?, + col: held.col as usize, + first: run.positions.start, + leaves: committed.leaves.clone(), + }) + } +} + +/// The leaves of a turn's prefix, in position order. +pub(super) fn prefix_leaves(prefix: &TurnPrefix) -> Vec { + prefix + .cells + .iter() + .zip(&prefix.positions) + .map(|(cell, position)| prefix_leaf(cell, position)) + .collect() +} + +/// The Merkle root over a turn's prefix cells, in position order, or `None` +/// for a turn that starts at position 0. +pub(crate) fn prefix_root(prefix: &TurnPrefix) -> Result> { + if prefix.is_empty() { + return Ok(None); + } + Ok(Some(MerkleTree::new(prefix_leaves(prefix))?.root())) +} + +/// The leaf of one prefix cell ([`commitment::prefix_leaf`]). It binds the +/// cell's position, index and digest and the digest of the position's +/// leaves, and not the cell's stream. +pub(super) fn prefix_leaf(cell: &PrefixCell, position: &Hash) -> Hash { + commitment::prefix_leaf(cell.pos, cell.cell, &cell.digest, position) +} + +#[cfg(test)] +#[path = "cells_tests.rs"] +mod tests; diff --git a/crates/skippy-receipts/src/recorder/cells_tests.rs b/crates/skippy-receipts/src/recorder/cells_tests.rs new file mode 100644 index 00000000..e0cbff67 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/cells_tests.rs @@ -0,0 +1,400 @@ +use super::*; + +fn hash(n: u8) -> Hash { + [n; 32] +} + +/// What a ubatch committed in a column whose cell digest is `n`. +fn committed(n: u8) -> Option { + let leaves: Arc<[Hash]> = Arc::from(vec![hash(n), hash(n.wrapping_add(100))]); + Some(ColumnLeaves { + cell: hash(n), + position: commitment::position_digest(&leaves), + leaves, + }) +} + +/// A ubatch of `columns`, each a sequence, a position and a cell; the token +/// at a position is 1000 more than the position. +fn record(columns: &[(i32, i32, u32)]) -> Arc { + Arc::new(UbatchRecord { + token: columns.iter().map(|(_, pos, _)| 1000 + pos).collect(), + seq: columns.iter().map(|(seq, _, _)| *seq).collect(), + pos: columns.iter().map(|(_, pos, _)| *pos).collect(), + output: vec![0; columns.len()], + cell: columns.iter().map(|(_, _, cell)| *cell).collect(), + n_kv: 64, + input: None, + }) +} + +/// Writes one ubatch whose column `i` committed digest `digests[i]`. +fn write(m: &mut CellMirror, columns: &[(i32, i32, u32)], digests: &[u8]) -> Arc { + let record = record(columns); + m.write_ubatch(&record, digests.iter().map(|&n| committed(n)).collect()); + record +} + +/// Writes positions `positions` of `seq` in one ubatch, to cells +/// `first_cell..`, each with its position as digest. +fn append(m: &mut CellMirror, seq: i32, positions: std::ops::Range, first_cell: u32) { + let columns: Vec<(i32, i32, u32)> = positions + .clone() + .zip(first_cell..) + .map(|(pos, cell)| (seq, pos, cell)) + .collect(); + let digests: Vec = positions.map(|pos| pos as u8).collect(); + write(m, &columns, &digests); +} + +fn cells_of(prefix: &TurnPrefix) -> Vec { + prefix.cells.iter().map(|c| c.cell).collect() +} + +#[test] +fn a_shared_prefix_is_the_sources_cells() { + let mut m = CellMirror::default(); + append(&mut m, 7, 0..4, 10); + m.seq_cp(7, 1, 0, 3); + let prefix = m.prefix(1, 3).unwrap(); + assert_eq!(cells_of(&prefix), vec![10, 11, 12]); + assert_eq!(prefix.tokens, vec![1000, 1001, 1002]); + assert!(m.prefix(1, 4).is_err(), "position 3 was not shared"); + // the source losing its cells leaves the shared ones to the copy + m.seq_rm(7, -1, -1); + assert_eq!(m.prefix(1, 3).unwrap(), prefix); + assert!(prefix.cells.iter().all(|c| m.holds(c))); + m.seq_rm(1, 2, -1); + assert!(m.prefix(1, 3).is_err(), "the sequence lost position 2"); + assert!(m.holds(&prefix.cells[2]), "a freed cell keeps its rows"); + write(&mut m, &[(4, 0, 12)], &[8]); + assert!(!m.holds(&prefix.cells[2]), "until it is written again"); + write(&mut m, &[(3, 0, 11)], &[9]); + assert!( + !m.holds(&prefix.cells[1]), + "a rewritten cell holds new rows" + ); +} + +#[test] +fn a_rewritten_cell_leaves_every_sequence_that_shared_it() { + let mut m = CellMirror::default(); + write(&mut m, &[(7, 0, 5)], &[1]); + m.seq_cp(7, 1, -1, -1); + m.seq_rm(7, -1, -1); + m.seq_rm(1, -1, -1); + write(&mut m, &[(2, 0, 5)], &[2]); + assert!(m.prefix(1, 1).is_err()); + assert_eq!(m.prefix(2, 1).unwrap().cells[0].digest, hash(2)); +} + +#[test] +fn unrecorded_rows_or_gaps_have_no_prefix() { + let mut m = CellMirror::default(); + write(&mut m, &[(1, 0, 0)], &[1]); + let unhashed = record(&[(1, 1, 1)]); + m.write_ubatch(&unhashed, vec![None]); + assert!(m.prefix(1, 1).is_ok()); + assert!(m.prefix(1, 2).is_err(), "unknown rows"); + // a position written past a gap is no append + write(&mut m, &[(1, 3, 3)], &[3]); + assert!(m.prefix(1, 1).is_err(), "the sequence has a gap"); + m.seq_keep(2); + assert!(m.prefix(1, 1).is_err()); +} + +// A prefix position can be replayed from the cells below its ubatch only +// when those are the cells the ubatch ran on. +#[test] +fn a_prefix_follows_the_cells_each_ubatch_ran_on() { + // two ubatches, the second on top of the first + let mut m = CellMirror::default(); + append(&mut m, 1, 0..3, 0); + append(&mut m, 1, 3..5, 3); + let prefix = m.prefix(1, 5).unwrap(); + assert_eq!(cells_of(&prefix), vec![0, 1, 2, 3, 4]); + let lineage = |m: &CellMirror, at: usize| m.lineage(&prefix.cells[at], &prefix.positions[at]); + let (low, high) = (lineage(&m, 1).unwrap(), lineage(&m, 4).unwrap()); + assert_eq!((low.first, low.col, low.writer()), (0, 1, 1)); + assert_eq!((high.first, high.col), (3, 1)); + assert_eq!(high.record.pos, vec![3, 4]); + + // a tail cut inside a ubatch, written again: the prefix holds half of + // the first ubatch, and the second ran on that half + m.seq_rm(1, 2, -1); + append(&mut m, 1, 2..4, 10); + let cut = m.prefix(1, 4).unwrap(); + assert_eq!(cells_of(&cut), vec![0, 1, 10, 11]); + assert_eq!( + m.lineage(&cut.cells[3], &cut.positions[3]).unwrap().first, + 2 + ); + // the cells the cut freed keep their rows, but hold no position of it + assert!(m.holds(&prefix.cells[2])); + + // a copy from 0 holds what the source held through the copied position + m.seq_cp(1, 2, 0, 3); + assert_eq!(cells_of(&m.prefix(2, 3).unwrap()), vec![0, 1, 10]); + // and a ubatch appended to the copy ran on the copy's cells + append(&mut m, 2, 3..4, 20); + assert_eq!(cells_of(&m.prefix(2, 4).unwrap()), vec![0, 1, 10, 20]); + // the source goes on by itself + assert_eq!(cells_of(&m.prefix(1, 4).unwrap()), vec![0, 1, 10, 11]); +} + +#[test] +fn cells_from_two_sources_have_no_prefix() { + let mut m = CellMirror::default(); + append(&mut m, 1, 0..2, 0); + append(&mut m, 2, 0..4, 10); + // sequence 3 takes position 0 and 1 of one request, 2 and 3 of another + m.seq_cp(1, 3, 0, 2); + assert!(m.prefix(3, 2).is_ok()); + m.seq_cp(2, 3, 2, 4); + let error = m.prefix(3, 4).unwrap_err(); + assert!(format!("{error:#}").contains("cannot follow"), "{error:#}"); + // until it is emptied and filled from one + m.seq_rm(3, -1, -1); + m.seq_cp(2, 3, 0, 4); + assert_eq!(cells_of(&m.prefix(3, 4).unwrap()), vec![10, 11, 12, 13]); +} + +#[test] +fn a_write_that_is_no_append_has_no_prefix() { + // a lower position written after a higher one: the higher position's + // ubatch did not run on the new cell + let mut m = CellMirror::default(); + append(&mut m, 1, 0..3, 0); + write(&mut m, &[(1, 1, 9)], &[9]); + assert!(m.prefix(1, 3).is_err()); + // a removal from the middle leaves a gap + let mut m = CellMirror::default(); + append(&mut m, 1, 0..4, 0); + m.seq_rm(1, 1, 2); + assert!(m.prefix(1, 1).is_err()); + // a ubatch whose positions skip one + let mut m = CellMirror::default(); + write(&mut m, &[(1, 0, 0), (1, 2, 2)], &[0, 2]); + assert!(m.prefix(1, 1).is_err()); + // each is forgotten when the sequence is emptied + m.seq_rm(1, -1, -1); + append(&mut m, 1, 0..2, 4); + assert!(m.prefix(1, 2).is_ok()); +} + +#[test] +fn a_ubatch_of_several_sequences_is_a_run_of_each() { + let mut m = CellMirror::default(); + append(&mut m, 1, 0..2, 0); + // a decode step of two lanes in one ubatch + let shared = write(&mut m, &[(2, 0, 10), (1, 2, 2), (2, 1, 11)], &[50, 2, 51]); + let one = m.prefix(1, 3).unwrap(); + let two = m.prefix(2, 2).unwrap(); + assert_eq!(cells_of(&one), vec![0, 1, 2]); + assert_eq!(cells_of(&two), vec![10, 11]); + let lineage = m.lineage(&two.cells[1], &two.positions[1]).unwrap(); + assert!(Arc::ptr_eq(&lineage.record, &shared)); + assert_eq!((lineage.col, lineage.first, lineage.writer()), (2, 0, 2)); + let lineage = m.lineage(&one.cells[2], &one.positions[2]).unwrap(); + assert_eq!((lineage.col, lineage.first, lineage.writer()), (1, 2, 1)); +} + +#[test] +fn the_lineage_of_a_cell_is_gone_with_what_it_held() { + let mut m = CellMirror::default(); + append(&mut m, 1, 0..2, 0); + let prefix = m.prefix(1, 2).unwrap(); + let cell = prefix.cells[1]; + assert!(m.lineage(&cell, &prefix.positions[1]).is_ok()); + // other leaves than the turn read + assert_eq!( + m.lineage(&cell, &hash(77)).unwrap_err(), + CellRecord::Overwritten + ); + m.seq_rm(1, -1, -1); + assert!(m.lineage(&cell, &prefix.positions[1]).is_ok(), "freed"); + write(&mut m, &[(5, 0, 1)], &[9]); + assert_eq!( + m.lineage(&cell, &prefix.positions[1]).unwrap_err(), + CellRecord::Overwritten + ); + m.memory_op(MemoryOp::Compact, (-1, -1), (-1, -1), &BTreeSet::new()); + assert_eq!( + m.lineage(&cell, &prefix.positions[1]).unwrap_err(), + CellRecord::Unknown + ); +} + +// A stage after the first keeps a ubatch's input rows for its cells, within +// a budget. Past it the oldest ubatch goes, and its cells have no prefix. +#[test] +fn a_ubatch_past_the_input_budget_has_no_prefix() { + let with_input = |columns: &[(i32, i32, u32)]| { + let mut record = UbatchRecord::clone(&record(columns)); + record.input = Some(crate::recorder::StageInput { + rows: vec![0; columns.len() * 8], + row_bytes: 8, + ggml_type: 0, + }); + Arc::new(record) + }; + let mut m = CellMirror::default(); + m.set_input_budget(40); + for (seq, cell) in [(1, 0), (2, 10), (3, 20)] { + let record = with_input(&[(seq, 0, cell), (seq, 1, cell + 1)]); + m.write_ubatch(&record, vec![committed(1), committed(2)]); + } + let error = m.prefix(1, 2).unwrap_err(); + assert!(format!("{error:#}").contains("no longer held"), "{error:#}"); + assert!(m.prefix(2, 2).is_ok() && m.prefix(3, 2).is_ok()); + // the cell still holds its rows: only its ubatch is gone + let cell = PrefixCell { + pos: 0, + stream: 0, + cell: 0, + digest: hash(1), + }; + assert!(m.holds(&cell)); + let leaves = committed(1).unwrap().position; + assert_eq!(m.lineage(&cell, &leaves).unwrap_err(), CellRecord::Dropped); +} + +// What the recorder could not follow costs only the cells it can have +// changed. +#[test] +fn an_event_forgets_only_the_cells_it_can_have_changed() { + let filled = || { + let mut m = CellMirror::default(); + append(&mut m, 1, 0..3, 0); + append(&mut m, 2, 0..3, 10); + // sequence 3 finished: its cells are free and keep their rows + write(&mut m, &[(3, 0, 20)], &[20]); + m.seq_rm(3, -1, -1); + m + }; + let cell = |pos: i32, cell: u32, n: u8| PrefixCell { + pos, + stream: 0, + cell, + digest: hash(n), + }; + let held = |m: &CellMirror, seq: i32| m.prefix(seq, 3).is_ok(); + let freed = cell(0, 20, 20); + + let mut m = filled(); + m.memory_op(MemoryOp::SeqShift, (1, -1), (1, -1), &BTreeSet::new()); + assert!(m.holds(&cell(0, 0, 0)), "position 0 was not shifted"); + assert_eq!(m.record(&cell(1, 1, 1)), CellRecord::Unknown); + assert!(held(&m, 2) && m.holds(&freed)); + assert!(m.prefix(1, 1).is_err(), "a shifted sequence has no prefix"); + + let mut m = filled(); + m.memory_op(MemoryOp::StateRead, (1, -1), (-1, -1), &BTreeSet::new()); + assert!(!held(&m, 1), "the sequence's cells were replaced"); + assert!(held(&m, 2), "another sequence's cells were not"); + assert_eq!( + m.record(&freed), + CellRecord::Unknown, + "a free cell may hold the loaded rows" + ); + // a ubatch on top of loaded rows did not run on recorded cells + append(&mut m, 1, 0..1, 30); + assert!(m.prefix(1, 1).is_err()); + + let mut m = filled(); + m.unseen_write(&BTreeSet::new()); + assert!(held(&m, 1) && held(&m, 2)); + assert_eq!(m.record(&freed), CellRecord::Unknown); + + // the cache writes a free pinned cell only when nothing else fits: it + // keeps its record, to be checked before an opening reads it + let mut m = filled(); + let pins = BTreeSet::from([KvCell { + stream: freed.stream, + cell: freed.cell, + }]); + m.unseen_write(&pins); + assert_eq!(m.record(&freed), CellRecord::Exposed); + assert!(m.holds(&freed) && held(&m, 1) && held(&m, 2)); + m.clear_exposed(&freed); + assert_eq!(m.record(&freed), CellRecord::Held); + + for op in [MemoryOp::Clear, MemoryOp::Compact] { + let mut m = filled(); + m.memory_op(op, (-1, -1), (-1, -1), &BTreeSet::new()); + assert!(!held(&m, 1) && !held(&m, 2) && !m.holds(&freed)); + // a cleared cache is empty; a compacted one holds what it held + append(&mut m, 1, 0..3, 0); + assert_eq!(held(&m, 1), op == MemoryOp::Clear, "{op:?}"); + } + let mut m = filled(); + m.memory_op(MemoryOp::StateRead, (-1, -1), (-1, -1), &BTreeSet::new()); + assert!(!held(&m, 1) && !held(&m, 2)); + + // a cell a later ubatch wrote is told from one the mirror lost + let mut m = filled(); + write(&mut m, &[(2, 3, 20)], &[99]); + assert_eq!(m.record(&freed), CellRecord::Overwritten); +} + +#[test] +fn the_prefix_root_binds_positions_cells_rows_and_leaves() { + let prefix = |pos: i32, cell: u32, digest: u8, leaves: u8| TurnPrefix { + cells: vec![PrefixCell { + pos, + stream: 0, + cell, + digest: hash(digest), + }], + positions: vec![hash(leaves)], + tokens: vec![7], + }; + let root = prefix_root(&prefix(0, 4, 1, 9)).unwrap().unwrap(); + for other in [ + prefix(1, 4, 1, 9), + prefix(0, 5, 1, 9), + prefix(0, 4, 2, 9), + prefix(0, 4, 1, 8), + ] { + assert_ne!(prefix_root(&other).unwrap().unwrap(), root); + } + assert_eq!(prefix_root(&TurnPrefix::default()).unwrap(), None); +} + +#[test] +fn a_cache_per_sequence_numbers_cells_per_stream() { + let mut m = CellMirror::default(); + m.set_streams(KvStreams::PerSequence); + write(&mut m, &[(1, 0, 0)], &[1]); + write(&mut m, &[(2, 0, 0)], &[2]); + let one = m.prefix(1, 1).unwrap().cells[0]; + let two = m.prefix(2, 1).unwrap().cells[0]; + assert_eq!((one.stream, one.cell, two.stream, two.cell), (1, 0, 2, 0)); + assert!(m.holds(&one) && m.holds(&two), "the streams share no cell"); + // a freed cell of sequence 2 keeps its rows, which a copy takes along + write(&mut m, &[(2, 1, 1)], &[3]); + m.seq_rm(2, 1, -1); + m.seq_cp(2, 3, -1, -1); + let copied = m.prefix(3, 1).unwrap().cells[0]; + assert_eq!((copied.stream, copied.cell, copied.digest), (3, 0, hash(2))); + assert!( + m.prefix(3, 2).is_err(), + "position 1 was freed before the copy" + ); + let freed = PrefixCell { + pos: 1, + stream: 3, + cell: 1, + digest: hash(3), + }; + assert!(m.holds(&freed)); + // the copy's lineage is the source's ubatch + let prefix = m.prefix(3, 1).unwrap(); + let lineage = m.lineage(&prefix.cells[0], &prefix.positions[0]).unwrap(); + assert_eq!(lineage.writer(), 2); + // a copy replaces what the destination held + m.seq_cp(1, 3, -1, -1); + assert_eq!(m.prefix(3, 1).unwrap().cells[0].digest, hash(1)); + assert!(!m.holds(&copied) && !m.holds(&freed)); + assert!(m.holds(&two), "the source keeps its cells"); +} diff --git a/crates/skippy-receipts/src/recorder/challenge_shape.rs b/crates/skippy-receipts/src/recorder/challenge_shape.rs new file mode 100644 index 00000000..58479439 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/challenge_shape.rs @@ -0,0 +1,85 @@ +//! Bounds the work a challenge asks of a stage, before the stage replays +//! anything. +//! +//! The stage that issued a receipt checks a challenge against the receipt +//! ([`crate::challenge::check_shape`]). A later stage holds only its own +//! commitment of the turn, so it checks what it can see: that the challenge +//! asks for no more layers, positions, head positions and attention picks +//! than a draw makes, all at positions of the turn it committed or of its +//! cached prefix. A stage then replays at most [`LAYERS_PER_CHALLENGE`] +//! layers at [`crate::challenge::POSITIONS_PER_LAYER`] positions of the turn +//! each, and the ubatches of at most [`crate::challenge::PREFIX_POSITIONS`] +//! positions of the prefix, whoever sends the challenge. + +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Result, bail}; + +use super::Recorder; +use crate::challenge::{ + ATTENTION_POSITIONS_PER_LAYER, HEAD_POSITIONS, LAYERS_PER_CHALLENGE, check_picked_positions, +}; +use crate::wire::Challenge; + +impl Recorder { + /// Refuses a challenge that asks this stage for more than a draw does, + /// or for positions outside the turn it committed. A turn the stage no + /// longer holds is a [`crate::wire::CannotOpen`]. + pub fn check_challenge(&self, challenge: &Challenge) -> Result<()> { + let turn = { + let state = self.lock(); + let turn = self.opening_turn(&state.committed, &challenge.receipt_id)?; + turn.position_start..turn.position_end + }; + if challenge.picks.len() > LAYERS_PER_CHALLENGE { + bail!( + "the challenge picks {} layers; a draw picks at most {LAYERS_PER_CHALLENGE}", + challenge.picks.len() + ); + } + let increasing = |values: &[u32]| values.windows(2).all(|pair| pair[0] < pair[1]); + let in_turn = |positions: &[u32]| positions.iter().all(|p| turn.contains(p)); + let layers: Vec = challenge.picks.iter().map(|p| p.layer).collect(); + if !increasing(&layers) { + bail!("the challenge's layers are not in increasing order"); + } + if self.holds_output + && let Some(layer) = layers.iter().find(|&&layer| layer >= self.layers.end) + { + bail!("no stage holds layer {layer}"); + } + check_picked_positions(&challenge.picks, &turn)?; + if challenge.head.len() > HEAD_POSITIONS + || !increasing(&challenge.head) + || !in_turn(&challenge.head) + { + bail!( + "the head positions are not at most {HEAD_POSITIONS} increasing positions of the turn" + ); + } + let mut seen = BTreeSet::new(); + let mut per_layer: BTreeMap = BTreeMap::new(); + for pick in &challenge.attention { + let picked = challenge + .picks + .iter() + .any(|p| p.layer == pick.layer && p.positions.contains(&pick.position)); + if !picked || !seen.insert((pick.layer, pick.position)) { + bail!( + "attention pick at position {} of layer {} is not one picked position, once", + pick.position, + pick.layer + ); + } + let count = per_layer.entry(pick.layer).or_default(); + *count += 1; + if *count > ATTENTION_POSITIONS_PER_LAYER { + bail!( + "layer {} has more than {ATTENTION_POSITIONS_PER_LAYER} attention picks", + pick.layer + ); + } + } + Ok(()) + } +} diff --git a/crates/skippy-receipts/src/recorder/event_log.rs b/crates/skippy-receipts/src/recorder/event_log.rs new file mode 100644 index 00000000..100ae5c0 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/event_log.rs @@ -0,0 +1,148 @@ +//! A turn's replay log: the ubatches that computed its sequence and the +//! removals between them, and what they leave at each position. +//! +//! The native cache names removed positions as `[p0, p1)`, where `p0 < 0` +//! starts at 0 and `p1 < 0` has no end ([`removed`]). Everything that reads +//! a log applies removals through this module, so a position a turn computed +//! and then removed is nowhere read as computed. + +use std::collections::BTreeMap; +use std::ops::Range; +use std::sync::Arc; + +use super::UbatchRecord; + +#[derive(Clone)] +pub(super) enum Event { + Ubatch(Arc), + SeqRm { p0: i32, p1: i32 }, +} + +impl Event { + pub(super) fn ubatch(&self) -> Option<&UbatchRecord> { + match self { + Self::Ubatch(record) => Some(record), + Self::SeqRm { .. } => None, + } + } + + /// Bytes the event keeps in a log. + pub(super) fn bytes(&self) -> usize { + match self { + Self::Ubatch(record) => record.bytes(), + Self::SeqRm { .. } => 8, + } + } +} + +/// The positions a removal of `[p0, p1)` drops. +pub(super) fn removed(p0: i32, p1: i32) -> Range { + p0.max(0)..if p1 < 0 { i32::MAX } else { p1 } +} + +/// Whether a removal of `[p0, p1)` drops `position`. +pub(super) fn removes(p0: i32, p1: i32, position: u32) -> bool { + i32::try_from(position).is_ok_and(|position| removed(p0, p1).contains(&position)) +} + +/// Whether a removal of `[p0, p1)` drops every position. +pub(super) fn removes_all(p0: i32, p1: i32) -> bool { + p0 <= 0 && p1 < 0 +} + +/// The column of a log that holds a position: its event and its column in +/// that ubatch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Written { + pub event: usize, + pub col: usize, +} + +/// By position of `seq`, the column that computed it last, for every +/// position no later removal dropped. +pub(super) fn last_writes(events: &[Event], seq: i32) -> BTreeMap { + let mut written = BTreeMap::new(); + for (event, entry) in events.iter().enumerate() { + match entry { + Event::Ubatch(record) => { + for (col, (&s, &pos)) in record.seq.iter().zip(&record.pos).enumerate() { + if s == seq + && let Ok(pos) = u32::try_from(pos) + { + written.insert(pos, Written { event, col }); + } + } + } + Event::SeqRm { p0, p1 } => { + written.retain(|&position, _| !removes(*p0, *p1, position)); + } + } + } + written +} + +/// The first position `seq` has in each ubatch of `events` that computed it. +pub(super) fn ubatch_starts(events: &[Event], seq: i32) -> Vec { + events + .iter() + .filter_map(Event::ubatch) + .filter_map(|record| { + record + .seq + .iter() + .zip(&record.pos) + .filter(|&(&s, _)| s == seq) + .filter_map(|(_, &p)| u32::try_from(p).ok()) + .min() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ubatch(seq: i32, positions: &[i32]) -> Event { + Event::Ubatch(Arc::new(UbatchRecord { + token: positions.iter().map(|p| 100 + p).collect(), + seq: vec![seq; positions.len()], + pos: positions.to_vec(), + output: vec![0; positions.len()], + cell: positions.iter().map(|&p| 10 + p as u32).collect(), + n_kv: 64, + input: None, + })) + } + + #[test] + fn a_removal_reads_its_bounds_as_the_native_cache_does() { + assert_eq!(removed(-1, -1), 0..i32::MAX); + assert_eq!(removed(3, -1), 3..i32::MAX); + assert_eq!(removed(-1, 4), 0..4); + assert!(removes(2, 4, 2) && removes(2, 4, 3)); + assert!(!removes(2, 4, 1) && !removes(2, 4, 4)); + assert!(removes(2, -1, u32::try_from(i32::MAX - 1).unwrap())); + assert!(removes_all(-1, -1) && removes_all(0, -1)); + assert!(!removes_all(1, -1) && !removes_all(0, 5)); + } + + // A position a turn computed and removed is not one it computed: it + // names no ubatch, token or cell. One it computed again names the later + // ubatch. + #[test] + fn a_removed_position_was_not_written() { + let events = vec![ + ubatch(7, &[0, 1, 2, 3]), + Event::SeqRm { p0: 2, p1: -1 }, + ubatch(7, &[2]), + ubatch(9, &[3]), + ]; + let written = last_writes(&events, 7); + assert_eq!(written.keys().copied().collect::>(), [0, 1, 2]); + assert_eq!(written[&1], Written { event: 0, col: 1 }); + assert_eq!(written[&2], Written { event: 2, col: 0 }); + assert!(!written.contains_key(&3), "position 3 was removed"); + assert_eq!(last_writes(&events, 9)[&3], Written { event: 3, col: 0 }); + assert_eq!(ubatch_starts(&events, 7), [0, 2]); + } +} diff --git a/crates/skippy-receipts/src/recorder/leaves.rs b/crates/skippy-receipts/src/recorder/leaves.rs new file mode 100644 index 00000000..414223ff --- /dev/null +++ b/crates/skippy-receipts/src/recorder/leaves.rs @@ -0,0 +1,251 @@ +//! Hashes the committed leaves of a ubatch. +//! +//! One BLAKE3 call runs on one core, and a ubatch holds two leaves per layer +//! for every column, so the work is split across cores. A unit is one layer +//! of one column (its residual and mixing leaves), or the stage output +//! residual of one column. +//! +//! A decode ubatch of one token is split as well, also when the device +//! already digested its values and the units hash in microseconds. Starting +//! the threads costs the recorder thread about 0.2 ms per ubatch, which it +//! has to spare: the decoding thread never waited for it in either case. But +//! hashing such a ubatch on the recorder thread alone made decode about 5% +//! slower on a two-stage CUDA split (Qwen3-4B, receipts on), although the +//! hashing itself got faster. Over that run the machine's cores spent about +//! 40% more time in their deepest idle state, whose exit takes a +//! millisecond, so the threads that decode woke later; the short-lived +//! threads keep the stage's cores from idling that deep. Keep the split +//! unless decode is measured without it. + +use std::num::NonZero; +use std::ops::Range; +use std::sync::{Arc, OnceLock}; + +use anyhow::{Context, Result}; + +use crate::commitment::{ + Hash, MixingDigest, ValueDigest, cell_digest, mixing_leaf_from, mixing_rest, position_digest, + residual_leaf_of, stored_leaf, +}; +use crate::layer_tensors::{GGML_F32, MIXING_KINDS, TensorKind, UbatchColumns}; + +/// Hashing threads per ubatch, at most. +const MAX_THREADS: usize = 8; +/// A thread is spawned only for at least this many units. +const MIN_UNITS_PER_THREAD: usize = 4; + +/// A unit's residual leaf, and for a layer its mixing leaf's halves. +type UnitLeaves = (Hash, Option); + +#[derive(Clone, Copy)] +struct MixingHalves { + rest: Hash, + stored: Hash, +} + +/// What a stage committed at one position. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct PositionLeaves { + /// The leaves, in slot order. The stage keeps them with the cell the + /// position was written to, so a later turn can open them. + pub leaves: Arc<[Hash]>, + /// The digest of the leaves ([`position_digest`]). + pub position: Hash, + /// Per layer, the half of its mixing leaf that is not stored rows + /// ([`mixing_rest`]), which opens the stored rows. + pub rests: Vec, + /// The digest of the cell the position was written to. + pub cell: Hash, +} + +impl PositionLeaves { + /// Bytes the position's hashes hold. + pub(super) fn bytes(&self) -> usize { + (self.leaves.len() + self.rests.len() + 2) * size_of::() + } +} + +struct Ubatch<'a> { + layers: Range, + pos: &'a [i32], + /// The ubatch's tokens, on the stage that holds layer 0. + tokens: Option<&'a [i32]>, + columns: &'a dyn UbatchColumns, +} + +impl Ubatch<'_> { + fn units_per_column(&self) -> usize { + self.layers.len() + 1 + } + + fn unit(&self, unit: usize) -> Result { + let per_column = self.units_per_column(); + let col = unit / per_column; + let layer = self.layers.start + u32::try_from(unit % per_column)?; + let position = u32::try_from(self.pos[col]).context("negative position")?; + if layer == self.layers.end { + let output = self.residual(layer, col)?; + return Ok((residual_leaf_of(position, layer, None, output), None)); + } + let residual = self + .residual(layer, col)? + .with_context(|| format!("layer {layer} reported no residual column"))?; + let token = match (layer, self.tokens) { + (0, Some(tokens)) => Some(tokens[col]), + _ => None, + }; + let residual = residual_leaf_of(position, layer, token, Some(residual)); + let (stored, rest): (Vec, Vec) = + mixing_digests(self.columns, layer, col) + .into_iter() + .partition(|d| d.kind == TensorKind::MixingStored); + let halves = MixingHalves { + rest: mixing_rest(&rest), + stored: stored_leaf(position, layer, &stored), + }; + Ok((residual, Some(halves))) + } + + fn residual(&self, layer: u32, col: usize) -> Result> { + match self.columns.column(layer, TensorKind::Residual, 0, col) { + Some(column) if column.ggml_type != GGML_F32 => { + anyhow::bail!("layer {layer} reported a residual that is not f32") + } + column => Ok(column.map(|c| c.value_digest())), + } + } + + fn units(&self, range: Range) -> Vec> { + range.map(|unit| self.unit(unit)).collect() + } + + fn hash_all(&self) -> Vec> { + let units = self.pos.len() * self.units_per_column(); + let threads = hashing_threads(units); + if threads <= 1 { + return self.units(0..units); + } + let chunk = units.div_ceil(threads); + std::thread::scope(|scope| { + let handles: Vec<_> = (0..units) + .step_by(chunk) + .map(|start| scope.spawn(move || self.units(start..(start + chunk).min(units)))) + .collect(); + handles + .into_iter() + .flat_map(|handle| handle.join().expect("a leaf hashing thread panicked")) + .collect() + }) + } +} + +/// Threads that hash `units` units: one, the calling thread, unless every +/// thread gets enough of them. +fn hashing_threads(units: usize) -> usize { + // the count reads cgroup files on Linux, too slow for every ubatch + static CPUS: OnceLock = OnceLock::new(); + let cpus = *CPUS.get_or_init(|| std::thread::available_parallelism().map_or(1, NonZero::get)); + cpus.min(MAX_THREADS) + .min(units / MIN_UNITS_PER_THREAD) + .max(1) +} + +/// The leaves of every column of a ubatch, in slot order, with the column's +/// position. A column with a missing tensor is an error. On the stage that +/// holds layer 0, the residual leaf of layer 0 binds each column's token. +pub(super) fn ubatch_leaves( + layers: Range, + pos: &[i32], + tokens: &[i32], + columns: &dyn UbatchColumns, +) -> Vec> { + let tokens = (layers.start == 0).then_some(tokens); + let ubatch = Ubatch { + layers, + pos, + tokens, + columns, + }; + let layers_start = ubatch.layers.start; + let per_column = ubatch.units_per_column(); + let mut hashed = ubatch.hash_all().into_iter(); + pos.iter() + .map(|&pos| { + // take every unit of the column, so the next column starts at its own + let units: Vec> = hashed.by_ref().take(per_column).collect(); + let units = units.into_iter().collect::>>()?; + let position = u32::try_from(pos).context("negative position")?; + Ok((position, position_leaves(position, layers_start, units)?)) + }) + .collect() +} + +/// The digests of a layer's committed mixing values at one column, in leaf +/// order. +fn mixing_digests(columns: &dyn UbatchColumns, layer: u32, col: usize) -> Vec { + MIXING_KINDS + .iter() + .flat_map(|&kind| { + (0..columns.count(layer, kind)).map(move |index| MixingDigest { + kind, + index, + value: columns + .column(layer, kind, index, col) + .map(|c| (c.ggml_type, c.value_digest())), + }) + }) + .collect() +} + +/// A position's leaves in slot order, its rests by layer and its cell +/// digest, from its units. +fn position_leaves( + position: u32, + layer_start: u32, + units: Vec, +) -> Result { + let mut leaves = Vec::with_capacity(2 * units.len()); + let mut rests = Vec::with_capacity(units.len()); + let mut stored = Vec::with_capacity(units.len()); + for (residual, halves) in units { + leaves.push(residual); + if let Some(halves) = halves { + let layer = layer_start + u32::try_from(rests.len())?; + leaves.push(mixing_leaf_from( + position, + layer, + &halves.rest, + &halves.stored, + )); + rests.push(halves.rest); + stored.push(halves.stored); + } + } + Ok(PositionLeaves { + position: position_digest(&leaves), + leaves: leaves.into(), + rests, + cell: cell_digest(stored)?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + // A decode ubatch of one token is split over threads like a prefill + // ubatch, whatever its values take to hash (see the module docs); only + // a ubatch of too few units is hashed on the calling thread. + #[test] + fn a_one_token_ubatch_is_split_over_threads() { + let cpus = std::thread::available_parallelism().map_or(1, NonZero::get); + let one_token = 18 + 1; + assert_eq!( + hashing_threads(one_token), + cpus.min(one_token / MIN_UNITS_PER_THREAD) + ); + assert_eq!(hashing_threads(512 * one_token), cpus.min(MAX_THREADS)); + assert_eq!(hashing_threads(MIN_UNITS_PER_THREAD), 1); + assert_eq!(hashing_threads(0), 1); + } +} diff --git a/crates/skippy-receipts/src/recorder/lineage.rs b/crates/skippy-receipts/src/recorder/lineage.rs new file mode 100644 index 00000000..989815fd --- /dev/null +++ b/crates/skippy-receipts/src/recorder/lineage.rs @@ -0,0 +1,324 @@ +//! The ubatches that wrote the cells a stage's KV cache holds, and stamps +//! that tell whether the cells below a ubatch are still the ones it ran on. +//! +//! A client may challenge a position of a turn's cached prefix. The stage +//! opens it by replaying the one ubatch that wrote the position, seeded +//! with the cells the sequence holds below that ubatch. That reproduces the +//! ubatch only when those cells are the ones the ubatch read. A sequence's +//! cells change in few ways, so a number per sequence is enough to tell: +//! +//! - an empty sequence has the stamp [`EMPTY`]; +//! - a ubatch that appends to a sequence notes the stamp it found +//! ([`Run::before`]) and leaves a stamp of that one and of itself +//! ([`Run::after`]); +//! - a sequence cut back to a position has the stamp its cells had when the +//! ubatch of that position ended, or a stamp of that one and the position +//! when the cut falls inside the ubatch ([`Runs::stamp_through`]); +//! - any other change leaves the sequence without a stamp +//! ([`Shape::UNREPLAYABLE`]) until it is emptied. +//! +//! Two sequences with the same stamp hold cells written by the same +//! ubatches in the same order. So a prefix position can be replayed when +//! the stamp its ubatch found is the stamp of the cells below it now. +//! +//! A stage after the first keeps the input rows of every recorded ubatch, +//! one residual row per token. The cells hold those ubatches alive, so the +//! rows are kept within a byte budget: past it, the oldest ubatch is +//! dropped, and its cells can no longer be opened as a prefix. + +use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::ops::Range; +use std::sync::Arc; + +use super::UbatchRecord; + +/// Identifies the cells a sequence holds, in order. +pub(super) type Stamp = u64; + +/// The stamp of a sequence that holds no cells. +pub(super) const EMPTY: Stamp = 0; + +const STAMP_DOMAIN: &[u8] = b"skippy-receipt-cell-stamp-v1"; +const APPENDED: u8 = 0; +const CUT: u8 = 1; +const UNFOLLOWED: u8 = 2; + +fn stamp(kind: u8, a: u64, b: u64) -> Stamp { + let mut h = blake3::Hasher::new(); + h.update(STAMP_DOMAIN); + h.update(&[kind]); + h.update(&a.to_le_bytes()); + h.update(&b.to_le_bytes()); + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(&h.finalize().as_bytes()[..8]); + Stamp::from_le_bytes(bytes) +} + +/// What the mirror knows of the cells a sequence holds, as a whole. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Shape { + pub stamp: Stamp, + /// The sequence holds positions from 0 without a gap, each appended to + /// the ones below it, so `stamp` identifies them. + pub replayable: bool, +} + +impl Shape { + /// A sequence whose cells a replay of one ubatch cannot start from. + pub const UNREPLAYABLE: Self = Self { + stamp: EMPTY, + replayable: false, + }; +} + +/// The positions one ubatch computed for one sequence. +pub(super) struct Run { + /// The ubatch as recorded, until the input budget drops it. + pub record: Option>, + /// The positions of the sequence the ubatch computed, in column order. + pub positions: Range, + /// The stamp of the sequence's cells below the run when it was + /// computed, or `None` when the run did not append to them. + pub before: Option, + /// The stamp of the sequence's cells through the run's last position. + pub after: Stamp, + /// Cells that still hold a position of the run. + cells: usize, + /// Bytes of input rows the run counts against the budget. + input_bytes: usize, +} + +/// The runs that wrote the cells of a mirror, by an id that grows with +/// time. +pub(super) struct Runs { + runs: HashMap, + next: u64, + /// Runs that hold input rows, oldest first. An id may name a run that + /// is gone. + with_input: VecDeque, + input_bytes: usize, + input_budget: usize, +} + +impl Default for Runs { + fn default() -> Self { + Self { + runs: HashMap::new(), + next: 0, + with_input: VecDeque::new(), + input_bytes: 0, + input_budget: super::DEFAULT_LINEAGE_INPUT_BYTES, + } + } +} + +impl Runs { + pub fn set_input_budget(&mut self, bytes: usize) { + self.input_budget = bytes; + self.enforce_budget(&BTreeSet::new()); + } + + pub fn get(&self, run: u64) -> Option<&Run> { + self.runs.get(&run) + } + + /// Forgets every run. Ids are not used again. + pub fn clear(&mut self) { + self.runs.clear(); + self.with_input.clear(); + self.input_bytes = 0; + } + + /// A ubatch computed `positions` of a sequence in `columns` of its + /// columns, on cells stamped `before`, or on cells it did not append to. + /// Returns the run's id and the stamp it leaves. + pub fn begin( + &mut self, + record: &Arc, + columns: usize, + positions: Range, + before: Option, + ) -> (u64, Stamp) { + let id = self.next; + self.next += 1; + let after = match before { + Some(before) => stamp(APPENDED, before, id), + None => stamp(UNFOLLOWED, id, 0), + }; + let input_bytes = record + .input + .as_ref() + .map_or(0, |input| columns * input.row_bytes); + if input_bytes > 0 { + self.input_bytes += input_bytes; + self.with_input.push_back(id); + } + self.runs.insert( + id, + Run { + record: Some(Arc::clone(record)), + positions, + before, + after, + cells: 0, + input_bytes, + }, + ); + (id, after) + } + + /// One more cell holds a position of `run`. + pub fn hold(&mut self, run: u64) { + if let Some(run) = self.runs.get_mut(&run) { + run.cells += 1; + } + } + + /// A cell that held a position of `run` holds it no longer. A run no + /// cell holds is forgotten. + pub fn release(&mut self, run: u64) { + let Some(entry) = self.runs.get_mut(&run) else { + return; + }; + entry.cells = entry.cells.saturating_sub(1); + if entry.cells == 0 { + if entry.record.is_some() { + self.input_bytes -= entry.input_bytes; + } + self.runs.remove(&run); + } + } + + /// The stamp of a sequence that holds the cells `run` ran on and the + /// run's positions through `position`. + pub fn stamp_through(&self, run: u64, position: i32) -> Option { + let run = self.runs.get(&run)?; + Some(if position + 1 == run.positions.end { + run.after + } else { + stamp(CUT, run.after, u64::from(position.unsigned_abs())) + }) + } + + /// Drops the recorded ubatch of the oldest runs while the input rows + /// the runs hold are past the budget, except those of `protected`: the + /// lineage of a turn a client can still challenge. Past the budget with + /// only those left, the newest run loses its ubatch, so a later turn + /// that reads its cells as its prefix gets no receipt. + pub fn enforce_budget(&mut self, protected: &BTreeSet) { + let mut kept = Vec::new(); + while self.input_bytes > self.input_budget { + let Some(id) = self.with_input.pop_front() else { + break; + }; + if protected.contains(&id) { + kept.push(id); + continue; + } + if let Some(run) = self.runs.get_mut(&id) + && run.record.take().is_some() + { + self.input_bytes -= run.input_bytes; + } + } + for id in kept.into_iter().rev() { + self.with_input.push_front(id); + } + // ids of runs that are gone would otherwise pile up + if self.with_input.len() > 2 * self.runs.len() + 64 { + self.with_input.retain(|id| { + self.runs + .get(id) + .is_some_and(|run| run.record.is_some() && run.input_bytes > 0) + }); + } + } + + /// Bytes of input rows the runs hold. + #[cfg(test)] + pub fn input_bytes(&self) -> usize { + self.input_bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::recorder::StageInput; + + fn record(columns: usize, row_bytes: usize) -> Arc { + Arc::new(UbatchRecord { + token: vec![0; columns], + seq: vec![1; columns], + pos: (0..columns as i32).collect(), + output: vec![0; columns], + cell: (0..columns as u32).collect(), + n_kv: 64, + input: (row_bytes > 0).then(|| StageInput { + rows: vec![0; columns * row_bytes], + row_bytes, + ggml_type: 0, + }), + }) + } + + #[test] + fn a_stamp_names_the_runs_below_and_where_they_were_cut() { + let mut runs = Runs::default(); + let (a, after_a) = runs.begin(&record(3, 0), 3, 0..3, Some(EMPTY)); + let (b, after_b) = runs.begin(&record(2, 0), 2, 3..5, Some(after_a)); + assert_eq!(runs.stamp_through(a, 2), Some(after_a)); + assert_eq!(runs.stamp_through(b, 4), Some(after_b)); + // a cut inside a run is a state of its own, one per position + let cut = runs.stamp_through(a, 1).unwrap(); + assert_ne!(cut, after_a); + assert_ne!(cut, runs.stamp_through(a, 0).unwrap()); + // the same ubatch on other cells leaves another stamp + let (_, on_cut) = runs.begin(&record(2, 0), 2, 2..4, Some(cut)); + assert_ne!(on_cut, after_b); + // a run that did not append has a stamp nothing else leaves + let (c, alone) = runs.begin(&record(1, 0), 1, 9..10, None); + assert_eq!(runs.get(c).unwrap().before, None); + assert_ne!(alone, EMPTY); + assert_eq!(runs.stamp_through(99, 0), None); + } + + #[test] + fn a_run_lives_while_a_cell_holds_it() { + let mut runs = Runs::default(); + let (a, _) = runs.begin(&record(2, 8), 2, 0..2, Some(EMPTY)); + runs.hold(a); + runs.hold(a); + assert_eq!(runs.input_bytes(), 16); + runs.release(a); + assert!(runs.get(a).is_some()); + runs.release(a); + assert!(runs.get(a).is_none()); + assert_eq!(runs.input_bytes(), 0); + } + + #[test] + fn the_oldest_input_rows_go_first_past_the_budget() { + let mut runs = Runs::default(); + runs.set_input_budget(40); + let ids: Vec = (0..3) + .map(|i| { + let (id, _) = runs.begin(&record(2, 8), 2, 2 * i..2 * i + 2, None); + runs.hold(id); + runs.enforce_budget(&BTreeSet::new()); + id + }) + .collect(); + assert_eq!(runs.input_bytes(), 32); + assert!(runs.get(ids[0]).unwrap().record.is_none()); + assert!(runs.get(ids[1]).unwrap().record.is_some()); + // a run without input rows costs nothing and is never dropped + let (free, _) = runs.begin(&record(64, 0), 64, 6..70, None); + runs.hold(free); + runs.enforce_budget(&BTreeSet::new()); + assert!(runs.get(free).unwrap().record.is_some()); + // a dropped run frees nothing twice + runs.release(ids[0]); + assert_eq!(runs.input_bytes(), 32); + } +} diff --git a/crates/skippy-receipts/src/recorder/openings.rs b/crates/skippy-receipts/src/recorder/openings.rs new file mode 100644 index 00000000..fdbbed06 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/openings.rs @@ -0,0 +1,284 @@ +//! Openings already answered, so a repeated challenge is not replayed again. +//! +//! An opening is kept until it is the least recently used past the byte +//! budget, or its turn leaves the opening window. + +use std::collections::VecDeque; +use std::sync::Arc; + +use crate::wire::{Challenge, LeafOpening, StageOpening, TensorOpening}; + +/// Bytes of openings kept, across turns. +const DEFAULT_OPENING_CACHE_BYTES: usize = 128 << 20; + +struct Entry { + challenge: Challenge, + opening: Arc, + bytes: usize, +} + +/// Least recently used last. +pub(super) struct OpeningCache { + entries: VecDeque, + bytes: usize, + budget: usize, +} + +impl Default for OpeningCache { + fn default() -> Self { + Self::new(DEFAULT_OPENING_CACHE_BYTES) + } +} + +impl OpeningCache { + pub(super) fn new(budget: usize) -> Self { + Self { + entries: VecDeque::new(), + bytes: 0, + budget, + } + } + + pub(super) fn get(&mut self, challenge: &Challenge) -> Option> { + let index = self + .entries + .iter() + .position(|entry| &entry.challenge == challenge)?; + let entry = self.entries.remove(index)?; + let opening = entry.opening.clone(); + self.entries.push_back(entry); + Some(opening) + } + + pub(super) fn insert(&mut self, challenge: Challenge, opening: Arc) { + let bytes = opening_bytes(&opening); + if bytes > self.budget { + return; + } + if let Some(index) = self + .entries + .iter() + .position(|entry| entry.challenge == challenge) + { + self.remove(index); + } + self.bytes += bytes; + self.entries.push_back(Entry { + challenge, + opening, + bytes, + }); + while self.bytes > self.budget { + self.remove(0); + } + } + + /// Drops every opening of a receipt. + pub(super) fn forget(&mut self, receipt_id: &str) { + let mut bytes = 0; + self.entries.retain(|entry| { + let keep = entry.challenge.receipt_id != receipt_id; + if !keep { + bytes += entry.bytes; + } + keep + }); + self.bytes -= bytes; + } + + fn remove(&mut self, index: usize) { + if let Some(entry) = self.entries.remove(index) { + self.bytes -= entry.bytes; + } + } +} + +fn opening_bytes(opening: &StageOpening) -> usize { + let paths = |path: &[String]| path.iter().map(String::len).sum::(); + let layers: usize = opening + .layers + .iter() + .flat_map(|layer| &layer.leaves) + .map(leaf_bytes) + .sum(); + let anchors: usize = opening + .anchors + .iter() + .map(|a| a.residual.len() + paths(&a.path)) + .sum(); + let boundaries: usize = opening + .entry + .iter() + .chain(&opening.exit) + .map(|b| b.leaf.len() + paths(&b.path)) + .sum(); + let head: usize = opening + .head + .iter() + .map(|h| h.residual.len() + h.logits.as_ref().map_or(0, String::len) + paths(&h.path)) + .sum(); + let prefix: usize = opening + .prefix + .iter() + .map(|p| paths(&p.leaves) + paths(&p.stored) + paths(&p.path)) + .sum(); + let tokens = opening.prefix_tokens.len() * size_of::(); + // grow with the context and with every position of a recurrent ubatch + let attention: usize = opening.attention.iter().map(|a| a.partials.len()).sum(); + let recurrent: usize = opening + .recurrent + .iter() + .flat_map(|r| &r.leaves) + .map(|leaf| tensors_bytes(&leaf.mixing) + paths(&leaf.path)) + .sum(); + layers + anchors + boundaries + head + prefix + tokens + attention + recurrent +} + +fn tensors_bytes(tensors: &[TensorOpening]) -> usize { + tensors + .iter() + .map(|t| t.values.as_ref().map_or(0, String::len)) + .sum() +} + +fn leaf_bytes(leaf: &LeafOpening) -> usize { + let paths = |path: &[String]| path.iter().map(String::len).sum::(); + leaf.residual_in.len() + + leaf.residual_out.as_ref().map_or(0, String::len) + + paths(&leaf.residual_in_path) + + paths(&leaf.mixing_path) + + paths(&leaf.residual_out_path) + + tensors_bytes(&leaf.mixing) + + leaf + .matrices + .iter() + .map(|m| { + m.weight.len() + + m.input.len() + + m.output.len() + + m.experts.as_ref().map_or(0, |e| e.len() * 4) + }) + .sum::() + + leaf + .selections + .iter() + .map(|s| s.ids.len() * 4) + .sum::() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire::{LayerOpening, Pick}; + + fn challenge(receipt: &str, layer: u32) -> Challenge { + Challenge { + receipt_id: receipt.into(), + picks: vec![Pick { + layer, + positions: vec![1, 2], + }], + proof: None, + head: Vec::new(), + attention: Vec::new(), + } + } + + fn opening(bytes: usize) -> Arc { + Arc::new(StageOpening { + stage_index: 0, + layers: vec![LayerOpening { + layer: 0, + leaves: vec![LeafOpening { + position: 1, + residual_in: "0".repeat(bytes), + residual_out: None, + residual_in_path: Vec::new(), + mixing_path: Vec::new(), + residual_out_path: Vec::new(), + mixing: Vec::new(), + matrices: Vec::new(), + selections: Vec::new(), + }], + }], + anchors: Vec::new(), + entry: Vec::new(), + exit: Vec::new(), + head: Vec::new(), + attention: Vec::new(), + recurrent: Vec::new(), + prefix: Vec::new(), + prefix_tokens: Vec::new(), + }) + } + + #[test] + fn the_least_recently_used_opening_goes_first() { + let mut cache = OpeningCache::new(25); + cache.insert(challenge("a", 1), opening(10)); + cache.insert(challenge("b", 1), opening(10)); + assert!(cache.get(&challenge("a", 1)).is_some()); + cache.insert(challenge("c", 1), opening(10)); + assert!(cache.get(&challenge("b", 1)).is_none()); + assert!(cache.get(&challenge("a", 1)).is_some()); + assert!(cache.get(&challenge("c", 1)).is_some()); + assert_eq!(cache.bytes, 20); + } + + #[test] + fn a_receipt_can_be_forgotten() { + let mut cache = OpeningCache::new(100); + cache.insert(challenge("a", 1), opening(10)); + cache.insert(challenge("a", 2), opening(10)); + cache.insert(challenge("b", 1), opening(10)); + cache.forget("a"); + assert!(cache.get(&challenge("a", 1)).is_none()); + assert!(cache.get(&challenge("b", 1)).is_some()); + assert_eq!(cache.bytes, 10); + } + + #[test] + fn attention_and_recurrent_payloads_count_against_the_budget() { + use crate::attention::opening::AttentionPartials; + use crate::wire::{MixingKind, MixingLeafOpening, RecurrentOpening}; + + let mut heavy = (*opening(0)).clone(); + heavy.attention.push(AttentionPartials { + position: 1, + layer: 0, + head: 0, + partials: "0".repeat(40), + }); + heavy.recurrent.push(RecurrentOpening { + position: 1, + layer: 0, + start: 0, + end: 2, + leaves: vec![MixingLeafOpening { + position: 0, + mixing: vec![TensorOpening { + kind: MixingKind::State, + index: 0, + ggml_type: 0, + values: Some("0".repeat(30)), + }], + path: vec!["0".repeat(10)], + }], + }); + assert_eq!(opening_bytes(&heavy), 80); + let mut cache = OpeningCache::new(50); + cache.insert(challenge("a", 1), Arc::new(heavy.clone())); + assert!(cache.get(&challenge("a", 1)).is_none(), "over the budget"); + let mut cache = OpeningCache::new(100); + cache.insert(challenge("a", 1), Arc::new(heavy)); + assert_eq!(cache.bytes, 80); + } + + #[test] + fn an_opening_over_the_budget_is_not_kept() { + let mut cache = OpeningCache::new(5); + cache.insert(challenge("a", 1), opening(10)); + assert!(cache.get(&challenge("a", 1)).is_none()); + assert_eq!(cache.bytes, 0); + } +} diff --git a/crates/skippy-receipts/src/recorder/pins.rs b/crates/skippy-receipts/src/recorder/pins.rs new file mode 100644 index 00000000..ae74a8fa --- /dev/null +++ b/crates/skippy-receipts/src/recorder/pins.rs @@ -0,0 +1,446 @@ +//! Which KV cells a stage keeps out of later requests' way, so a turn a +//! client may still challenge can be opened. +//! +//! A pinned cell is skipped while a request fits elsewhere, so the cache's +//! attention window grows by the pinned cells and every later request +//! reads them as masked rows. On back-to-back Qwen3-4B requests, pinning +//! every turn for 30 seconds slowed decode by about 5%. So a stage pins a +//! turn only while a client can still challenge it, while a challenge of it +//! waits and is opened, and once opened, until the client has the rows of +//! its attention blocks. +//! +//! A client may challenge a turn for [`CHALLENGE_PIN`], and most do at +//! once. So a turn is held firmly for [`FIRM_PIN`]: nothing but the caps +//! below takes its pin, and no room is made at its cost. After that it +//! lingers: it stays pinned and openable while that costs later requests +//! little, and gives way, oldest first, when lingering turns pin more than +//! [`LINGERING_SHARE`] of a stream or the stage needs the memory they hold. +//! A client that challenges a lingering turn that gave way gets a signed +//! answer that says so. +//! +//! Pins are capped, so a client that sends bound long-prompt turns cannot +//! keep the cache pinned at no cost: a client key pins at most +//! [`PINNED_SHARE_PER_KEY`] of a stream's cells, and all turns together +//! [`PINNED_SHARE`]. A new turn always gets its pin, because a turn +//! without a receipt costs an honest node a strike in Mesh. Past a share, +//! the oldest pins give way ([`Recorder::admit_pin`]). + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::{Duration, Instant}; + +use anyhow::{Result, bail}; + +use super::cells::CellMirror; +use super::{ + CommittedTurn, KvCell, PrefixCell, Recorder, attention_opening::written_cells, turn, turn_mut, +}; +use crate::attention::opening::ROWS_PIN; + +/// How long after its commit an unchallenged turn stays pinned, at most: +/// the client's 10-minute challenge window, and 2 seconds for the response +/// to reach it and the challenge to come back. A client that audits many +/// turns may have a queue of them to challenge. +pub const CHALLENGE_PIN: Duration = Duration::from_secs(602); + +/// How long after its commit an unchallenged turn is held whatever room it +/// takes: the 10 seconds in which a client that challenges at once does, +/// and 2 seconds for the response to reach it and the challenge to come +/// back. From then until [`CHALLENGE_PIN`] the turn lingers. +pub const FIRM_PIN: Duration = Duration::from_secs(12); + +/// How long a turn stays pinned, at most, from the moment a challenge of +/// it arrives until its opening ends ([`Recorder::hold_for_opening`]): the +/// 15 seconds a client waits for an opening, and 5 for the challenge to +/// arrive and the opening to reach it. A turn of a long prompt replays +/// for seconds, and its opening reads the turn's cells after the replay, +/// so the cells must still hold what the turn wrote then, also past +/// [`CHALLENGE_PIN`]. +pub const OPENING_PIN: Duration = Duration::from_secs(20); + +/// The share of a stream's KV cells that all pinned turns may hold: a +/// quarter of the cache stays free of pins for the requests being served. +pub const PINNED_SHARE: (u64, u64) = (3, 4); +/// The share of a stream's KV cells the pinned turns of one client key may +/// hold, so one key cannot take the whole of [`PINNED_SHARE`]. +pub const PINNED_SHARE_PER_KEY: (u64, u64) = (1, 2); +/// The share of a stream's KV cells that lingering turns may pin: what a +/// late challenge is worth to the requests served meanwhile, which read +/// every pinned cell as a masked row. +pub const LINGERING_SHARE: (u64, u64) = (1, 4); + +/// Whether a committed turn's cells are pinned. +#[derive(Clone, Copy, Debug)] +pub(super) struct Pin { + committed_at: Instant, + /// When the latest challenge of the turn arrived, while one is being + /// opened. + opening_since: Option, + /// The challenges of the turn that hold it for their opening: each + /// request holds the pin until its own opening ends, so one that is + /// turned away cannot release the pin of one being replayed. + openings: u32, + opened_at: Option, + released: bool, + /// The client key the turn is bound to, once its pin was admitted. + client_key: Option<[u8; 32]>, +} + +impl Pin { + pub(super) fn new(committed_at: Instant) -> Self { + Self { + committed_at, + opening_since: None, + openings: 0, + opened_at: None, + released: false, + client_key: None, + } + } + + pub(super) fn holds(&self, now: Instant) -> bool { + self.expiry().is_some_and(|expiry| now < expiry) + } + + /// Whether the pin holds and nothing may take it for room: a client + /// challenged the turn, or may still do so at once. + pub(super) fn firm(&self, now: Instant) -> bool { + self.holds(now) && (self.challenged() || now < self.committed_at + FIRM_PIN) + } + + /// Whether the pin holds past [`FIRM_PIN`] with no challenge: it gives + /// way when what the turn holds is needed. + pub(super) fn lingers(&self, now: Instant) -> bool { + self.holds(now) && !self.firm(now) + } + + /// When the pin next changes by itself, while it holds: it starts to + /// linger, or runs out. + fn next_change(&self, now: Instant) -> Option { + let expiry = self.expiry().filter(|expiry| now < *expiry)?; + let lingers_from = self.committed_at + FIRM_PIN; + Some(match !self.challenged() && now < lingers_from { + true => lingers_from.min(expiry), + false => expiry, + }) + } + + /// A challenge of the turn arrived: its cells are pinned until the + /// opening ends, for [`OPENING_PIN`] at most, also when its pin was + /// released or gave way. A turn already opened keeps the pin of its rows. + fn opening(&mut self, now: Instant) { + self.openings = self.openings.saturating_add(1); + if self.opened_at.is_none() { + self.opening_since = Some(now); + } + } + + /// One challenge's opening ended; the pin holds for the others. + fn opening_ended(&mut self) { + self.openings = self.openings.saturating_sub(1); + if self.openings == 0 { + self.opening_since = None; + } + } + + /// Whether a client challenged the turn: it is being opened, or was. + fn challenged(&self) -> bool { + self.opening_since.is_some() || self.opened_at.is_some() + } + + /// The turn was opened: with attention partials, it stays pinned until + /// their rows are opened; without, nothing will ask for its rows. + pub(super) fn opened(&mut self, now: Instant, partials: bool) { + // an opening still running holds the pin until it ends + if self.openings == 0 { + self.opening_since = None; + } + if partials { + self.opened_at = Some(now); + } else { + self.released = true; + } + } + + pub(super) fn release(&mut self) { + self.released = true; + } + + /// Makes the pin `by` older, as if its turn was committed that long ago. + #[cfg(test)] + pub(super) fn age(&mut self, by: Duration) { + self.committed_at = self + .committed_at + .checked_sub(by) + .expect("a clock that started before the turn"); + } + + /// When the pin stops holding by itself, while it holds. + fn expiry(&self) -> Option { + // a turn being opened holds its pin whatever happened to it before + if let (None, Some(since)) = (self.opened_at, self.opening_since) { + return Some(since + OPENING_PIN); + } + if self.released { + return None; + } + Some(match self.opened_at { + Some(at) => at + ROWS_PIN, + None => self.committed_at + CHALLENGE_PIN, + }) + } +} + +impl Recorder { + /// The cells that a pinned turn's opening would read and that still + /// hold what the turn read or wrote. The stage pins them, so a later + /// request writes other cells while it fits there. + pub fn pinned_cells(&self, now: Instant) -> Vec { + let mut state = self.lock(); + state.shed_lingering_pins(now); + let pinned: BTreeSet = state + .committed + .iter() + .filter(|t| t.pin.holds(now)) + .flat_map(|turn| turn_pin_cells(&state.cells, turn)) + .collect(); + let cells = pinned.iter().copied().collect(); + state.pins = pinned; + cells + } + + /// Sets how many cells a stream of the stage's KV cache has, which the + /// cells pinned for challenges are a share of ([`Self::admit_pin`]). + /// Zero, the default, caps nothing. + pub fn set_pin_budget(&self, cells_per_stream: u32) { + self.lock().pin_budget = cells_per_stream; + } + + /// Admits the pin of the committed turn `receipt_id`, bound to + /// `client_key`. Pinned cells slow every later request and are written + /// anyway once the cache is full, so a client key pins at most + /// [`PINNED_SHARE_PER_KEY`] of a stream, and every key together + /// [`PINNED_SHARE`]. The new turn always gets its pin: a serving node + /// owes its client a receipt it can open. Older pins give way for it + /// ([`pins_to_release`]), and a turn that is past a share alone is + /// pinned alone. + pub fn admit_pin(&self, receipt_id: &str, client_key: [u8; 32], now: Instant) -> Result<()> { + let mut state = self.lock(); + let budget = state.pin_budget; + let Some(turn) = turn(&state.committed, receipt_id) else { + bail!("receipt {receipt_id} is not committed"); + }; + if budget > 0 { + let own: BTreeSet = turn_pin_cells(&state.cells, turn).collect(); + let mut held: Vec = state + .committed + .iter() + .filter(|t| t.receipt_id != receipt_id && t.pin.holds(now)) + .map(|other| HeldPin { + receipt_id: other.receipt_id.clone(), + opened: other.pin.challenged(), + committed_at: other.pin.committed_at, + same_key: other.pin.client_key == Some(client_key), + cells: turn_pin_cells(&state.cells, other).collect(), + }) + .collect(); + // a stable sort: turns committed at the same instant keep their order + held.sort_by_key(|pin| (pin.opened, pin.committed_at)); + for released in pins_to_release(&own, held, budget) { + if let Some(turn) = turn_mut(&mut state.committed, &released) { + turn.pin.release(); + } + } + state.shed_lingering_pins(now); + state.drop_unpinned_states(now); + } + if let Some(turn) = turn_mut(&mut state.committed, receipt_id) { + turn.pin.client_key = Some(client_key); + } + Ok(()) + } + + /// The stage could not pin the cells [`Self::pinned_cells`] named: as far + /// as a write the recorder does not see goes, no cell is pinned. + pub fn pins_not_applied(&self) { + self.lock().pins.clear(); + } + + /// When the next pinned turn's pin runs out or starts to linger, so the + /// stage can pin anew then and not hold the turn's cells until its next + /// commit. `None` when no turn is pinned. + pub fn next_pin_expiry(&self, now: Instant) -> Option { + self.lock() + .committed + .iter() + .filter_map(|turn| turn.pin.next_change(now)) + .min() + } + + /// Stops pinning a turn's cells: no client can challenge it, or the + /// client has its rows. + pub fn release_pin(&self, receipt_id: &str) { + let mut state = self.lock(); + if let Some(turn) = turn_mut(&mut state.committed, receipt_id) { + turn.pin.release(); + } + state.drop_unpinned_states(Instant::now()); + } + + /// A challenge of the turn `receipt_id` arrived at `now`: its cells are + /// pinned until [`Self::end_opening`], for [`OPENING_PIN`] at most, + /// whether or not its own pin still holds. The cells it pins are + /// those that still hold what the turn read or wrote. + pub fn hold_for_opening(&self, receipt_id: &str, now: Instant) { + if let Some(turn) = turn_mut(&mut self.lock().committed, receipt_id) { + turn.pin.opening(now); + } + } + + /// The opening of the turn `receipt_id` ended. An opening that read + /// attention partials pinned the turn for its rows; any other leaves the + /// turn its challenge pin, which has most likely run out. + pub fn end_opening(&self, receipt_id: &str) { + let mut state = self.lock(); + if let Some(turn) = turn_mut(&mut state.committed, receipt_id) { + turn.pin.opening_ended(); + } + state.drop_unpinned_states(Instant::now()); + } +} + +impl super::RecorderState { + /// Releases the pins of lingering turns, oldest first, while they pin + /// more than [`LINGERING_SHARE`] of a stream's cells beside what the + /// turns held firmly pin: a cell a firm turn pins costs nothing more + /// when a lingering turn reads it too. A lingering turn none of whose + /// cells still holds what it wrote is released as well: nothing is left + /// to pin for it, and it would be looked at again at every pin. + pub(super) fn shed_lingering_pins(&mut self, now: Instant) { + let budget = u64::from(self.pin_budget); + if budget == 0 || !self.committed.iter().any(|turn| turn.pin.lingers(now)) { + return; + } + let mut pinned: BTreeSet = self + .committed + .iter() + .filter(|turn| turn.pin.firm(now)) + .flat_map(|turn| turn_pin_cells(&self.cells, turn)) + .collect(); + let (num, den) = LINGERING_SHARE; + let mut lingering: BTreeMap = BTreeMap::new(); + let mut released = Vec::new(); + // newest first, so the turns that fit the share are the newest + for (index, turn) in self.committed.iter().enumerate().rev() { + if !turn.pin.lingers(now) { + continue; + } + let cells: Vec = turn_pin_cells(&self.cells, turn).collect(); + let mut added: BTreeMap = BTreeMap::new(); + for cell in cells.iter().filter(|cell| !pinned.contains(cell)) { + *added.entry(cell.stream).or_default() += 1; + } + let over = added.iter().any(|(stream, more)| { + (lingering.get(stream).copied().unwrap_or(0) + more) * den > budget * num + }); + if cells.is_empty() || over { + released.push(index); + continue; + } + for (stream, more) in added { + *lingering.entry(stream).or_default() += more; + } + pinned.extend(cells); + } + for index in released { + self.committed[index].pin.release(); + } + } +} + +/// The cells of `turn` an opening reads that still hold what it read or +/// wrote: its prefix cells and the cells it wrote last. +fn turn_pin_cells<'a>( + mirror: &'a CellMirror, + turn: &'a CommittedTurn, +) -> impl Iterator + 'a { + let written = written_cells(turn); + let stream = mirror.streams().of(turn.seq); + let own = turn + .cells + .iter() + .zip(turn.position_start..) + .filter_map(move |(c, pos)| { + Some(PrefixCell { + pos: i32::try_from(pos).ok()?, + stream, + cell: *written.get(&pos)?, + digest: c.digest, + }) + }); + turn.prefix + .cells + .iter() + .copied() + .chain(own) + .filter(|c| mirror.holds(c)) + .map(|c| KvCell { + stream: c.stream, + cell: c.cell, + }) +} + +/// A pin that holds beside the turn being admitted. +struct HeldPin { + receipt_id: String, + /// The turn was opened and waits for its rows request. + opened: bool, + committed_at: Instant, + /// Bound to the client key of the turn being admitted. + same_key: bool, + cells: Vec, +} + +/// The pins that give way so the turn that pins `own` fits the shares of +/// `budget`, out of `held` in the order they give way: turns no client +/// has challenged before turns that wait for their rows request, and the +/// oldest first. Most turns are never challenged, and a client that +/// challenges does so soon after the response, so the oldest unchallenged +/// turn is the one least likely to be opened. A released turn stays +/// openable until a ubatch writes its cells. +/// +/// Past its key's share, the pins of that key give way; past the share of +/// all keys, the pins of any key. A turn that is past a share with no +/// other pin left keeps its own. +fn pins_to_release(own: &BTreeSet, mut held: Vec, budget: u32) -> Vec { + let mut released = Vec::new(); + loop { + let mut by_key = own.clone(); + let mut all = own.clone(); + for pin in &held { + if pin.same_key { + by_key.extend(pin.cells.iter().copied()); + } + all.extend(pin.cells.iter().copied()); + } + let of_key = over_share(&by_key, budget, PINNED_SHARE_PER_KEY) + .and_then(|_| held.iter().position(|pin| pin.same_key)); + let next = of_key.or_else(|| { + over_share(&all, budget, PINNED_SHARE).and_then(|_| (!held.is_empty()).then_some(0)) + }); + let Some(index) = next else { + return released; + }; + released.push(held.remove(index).receipt_id); + } +} + +/// The most cells `cells` pins in one stream, when that is past `share` of +/// the stream's `budget` cells. +fn over_share(cells: &BTreeSet, budget: u32, (num, den): (u64, u64)) -> Option { + let mut per_stream: BTreeMap = BTreeMap::new(); + for cell in cells { + *per_stream.entry(cell.stream).or_default() += 1; + } + let most = per_stream.into_values().max()?; + (most as u64 * den > u64::from(budget) * num).then_some(most) +} diff --git a/crates/skippy-receipts/src/recorder/prefix_opening.rs b/crates/skippy-receipts/src/recorder/prefix_opening.rs new file mode 100644 index 00000000..39d46625 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/prefix_opening.rs @@ -0,0 +1,178 @@ +//! Opens the picked positions of a turn's cached prefix. +//! +//! A turn did not compute its prefix, so a replay of the turn does not +//! recompute it. Each cell of the stage's cache keeps the ubatch that wrote +//! it ([`super::cells`]). For a picked position of the prefix the stage +//! replays that one ubatch, from a copy of the prefix cells below it, which +//! are the cells the ubatch ran on. The replay is checked against the +//! leaves the stage committed when the ubatch ran, like a replay of the +//! turn against the turn's tree. +//! +//! Another sequence may have computed the prefix: a cache sequence, or an +//! earlier request whose cells the turn's sequence shares. The replay runs +//! in the turn's sequence all the same, so the ubatch's columns of the +//! writer are renamed to it ([`lineage_columns`]). +//! +//! The leaves of a prefix position are in no tree of the turn. The stage +//! opens them all, by hash, with the leaves of the rows the cell stores and +//! the position's path in the prefix tree the receipt commits +//! ([`PrefixOpening`]). + +use std::collections::BTreeMap; +use std::sync::Arc; + +use anyhow::{Context, Result}; + +use super::cells::{CellMirror, Lineage, TurnPrefix, prefix_leaves}; +use super::stage_opening::{Replay, replay_columns, seed_for}; +use super::{CommittedTurn, PrefixCell, Recorder, ReplayStep, Replayer, UbatchRecord}; +use crate::commitment::{Hash, MerkleTree, encode_path}; +use crate::wire::PrefixOpening; + +/// The picked positions of a turn's cached prefix: the turn's prefix, and +/// by position the leaves the stage committed when it computed it. +pub(super) struct PrefixPlan { + prefix: TurnPrefix, + picked: BTreeMap>, +} + +impl PrefixPlan { + /// The plan for the positions `lineage` holds, or `None` for none. + pub(super) fn of(turn: &CommittedTurn, lineage: &BTreeMap) -> Option { + (!lineage.is_empty()).then(|| Self { + prefix: turn.prefix.clone(), + picked: lineage + .iter() + .map(|(&position, found)| (position, Arc::clone(&found.leaves))) + .collect(), + }) + } +} + +impl Recorder { + /// How each of `positions` below the turn was computed, by position. A + /// cell that no longer holds the position, or whose ubatch the stage + /// dropped, is a [`crate::wire::CannotOpen`]. + pub(super) fn lineage( + &self, + turn: &CommittedTurn, + cells: &CellMirror, + positions: &[u32], + ) -> Result> { + positions + .iter() + .filter(|&&position| position < turn.position_start) + .map(|&position| { + let at = position as usize; + let (cell, digest) = turn + .prefix + .cells + .get(at) + .zip(turn.prefix.positions.get(at)) + .with_context(|| format!("position {position} is outside the prefix"))?; + let found = cells + .lineage(cell, digest) + .map_err(|record| self.lost_cell(cell, record))?; + Ok((position, found)) + }) + .collect() + } + + /// What the stage committed at each picked position of the prefix: its + /// leaves, the leaves of the rows its cell stores, read from the cache, + /// and its path in the prefix tree. + pub(super) fn open_prefix( + &self, + plan: Option<&PrefixPlan>, + replayer: &dyn Replayer, + ) -> Result> { + let Some(PrefixPlan { prefix, picked }) = plan else { + return Ok(Vec::new()); + }; + let cells: Vec = picked + .keys() + .map(|&position| prefix.cells[position as usize]) + .collect(); + self.check_cells(&cells)?; + let stored = self.prefix_trees(replayer, &cells)?; + let tree = MerkleTree::new(prefix_leaves(prefix))?; + picked + .iter() + .zip(&cells) + .map(|((&position, leaves), cell)| { + let stored = stored + .get(&position) + .context("the rows of a picked prefix cell were not read")?; + Ok(PrefixOpening { + position, + cell: cell.cell, + leaves: leaves.iter().map(hex::encode).collect(), + stored: (0..stored.leaf_count()) + .filter_map(|layer| stored.leaf(layer)) + .map(hex::encode) + .collect(), + path: encode_path(&tree.path(u64::from(position))?), + }) + }) + .collect() + } +} + +/// The replays of the picked positions of `turn`'s prefix: for each ubatch +/// that wrote one, that ubatch alone, from the prefix cells below it. +/// Positions one ubatch wrote share a replay. +pub(super) fn lineage_replays( + turn: &CommittedTurn, + lineage: &BTreeMap, +) -> Vec { + let mut by_ubatch: Vec<(&Lineage, Vec)> = Vec::new(); + for (&position, found) in lineage { + let same = |other: &Lineage| { + Arc::ptr_eq(&other.record, &found.record) && other.writer() == found.writer() + }; + match by_ubatch.iter_mut().find(|(other, _)| same(other)) { + Some((_, positions)) => positions.push(position), + None => by_ubatch.push((found, vec![position])), + } + } + by_ubatch + .into_iter() + .map(|(found, capture)| { + let steps = vec![ReplayStep::Decode { + record: lineage_columns(&found.record, found.writer(), turn.seq), + capture, + mixing: Vec::new(), + }]; + let below = usize::try_from(found.first).unwrap_or(0); + let cells = turn.prefix.cells[..below.min(turn.prefix.len())].to_vec(); + let seed = (!cells.is_empty()).then(|| seed_for(cells, &steps, None)); + Replay { seed, steps } + }) + .collect() +} + +/// A ubatch that computed positions for `writer`, as `seq` replays it: the +/// columns of `writer` become columns of `seq`, at their recorded +/// positions and cells, and every other column a dummy. The prefix of +/// `seq` shares the cells `writer` wrote, so a replay of `seq` from the +/// cells below the ubatch computes what `writer` did. +pub(super) fn lineage_columns( + record: &Arc, + writer: i32, + seq: i32, +) -> Arc { + if writer == seq { + return replay_columns(record, seq); + } + let mut renamed = UbatchRecord::clone(record); + for s in &mut renamed.seq { + // a column the ubatch computed for `seq` itself is another + // request's, and must not join the replayed sequence + *s = match *s { + s if s == writer => seq, + s if s == seq => writer, + s => s, + }; + } + replay_columns(&Arc::new(renamed), seq) +} diff --git a/crates/skippy-receipts/src/recorder/prefix_tests.rs b/crates/skippy-receipts/src/recorder/prefix_tests.rs new file mode 100644 index 00000000..ddb06e51 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/prefix_tests.rs @@ -0,0 +1,359 @@ +//! A stage opens a picked position of a turn's cached prefix by replaying +//! the one ubatch that wrote it, on the test model of `tests.rs`. + +use super::*; + +/// The decode step of a replay, as the replayer was given it. +fn decode(step: &ReplayStep) -> (&UbatchRecord, &[u32]) { + match step { + ReplayStep::Decode { + record, capture, .. + } => (record, capture), + ReplayStep::SeqRm { .. } => panic!("a decode step"), + } +} + +/// Sequence 7 computes three positions, then a turn of two more. +fn continued_turn() -> (Node, Receipt) { + let node = Node::new(); + node.record(ubatch(&[(7, 0), (7, 1), (7, 2)], &[0, 1, 2], true)); + node.commit(7, 0..3, 3); + node.record(ubatch(&[(7, 3)], &[3], true)); + node.record(ubatch(&[(7, 4)], &[4], true)); + let receipt = node.commit(7, 3..5, 4); + (node, receipt) +} + +#[test] +fn a_prefix_position_is_opened_by_replaying_its_ubatch() { + let (node, receipt) = continued_turn(); + verify_shape(&receipt, MODEL_LAYERS).unwrap(); + // the stage that holds layer 0 commits the prefix's tokens + let prefix = |stage: usize| receipt.stages[stage].prefix.clone().unwrap(); + assert_eq!((prefix(0).positions, prefix(1).positions), (3, 3)); + assert!(prefix(0).tokens.is_some() && prefix(1).tokens.is_none()); + + let challenge = challenge(&[(1, &[1, 4]), (3, &[1, 4])]); + let opening = node.open(&challenge).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + assert_eq!(opening.stages[0].prefix_tokens, vec![1000, 1001, 1002]); + assert!(opening.stages[1].prefix_tokens.is_empty()); + for stage in &opening.stages { + let opened: Vec = stage.prefix.iter().map(|p| p.position).collect(); + assert_eq!(opened, [1]); + assert_eq!(stage.prefix[0].cell, 1); + // a leaf of the prefix has no path + assert!(stage.layers[0].leaves[0].mixing_path.is_empty()); + assert!(!stage.layers[0].leaves[1].mixing_path.is_empty()); + assert!(stage.exit[0].path.is_empty()); + } + assert_eq!(opening.stages[0].anchors[0].token, 1001); + assert!(opening.stages[0].anchors[0].path.is_empty()); + // the turn is replayed from its prefix and its own cells; the ubatch of + // position 1 began at position 0, so it is replayed from nothing + let runs = node.replayers[1].runs.borrow(); + assert_eq!( + *runs, + vec![ + (vec![0, 1, 2, 3], vec![vec![4]]), + (Vec::new(), vec![vec![1]]) + ] + ); + // a stage after the first replays the ubatch from its recorded input + let steps = node.replayers[1].steps.borrow(); + assert_eq!(decode(&steps[0]).0.input.as_ref().unwrap().rows.len(), 12); +} + +#[test] +fn a_prefix_position_of_another_ubatch_is_replayed_from_the_cells_below_it() { + let node = Node::new(); + node.record(ubatch(&[(7, 0), (7, 1)], &[0, 1], true)); + node.record(ubatch(&[(7, 2), (7, 3)], &[2, 3], true)); + node.commit(7, 0..4, 4); + node.record(ubatch(&[(7, 4)], &[4], true)); + let receipt = node.commit(7, 4..5, 4); + // both positions of the second ubatch, and one of the first + for (picked, expected) in [ + (vec![2, 3, 4], vec![(vec![0, 1], vec![vec![2, 3]])]), + ( + vec![1, 3, 4], + vec![(Vec::new(), vec![vec![1]]), (vec![0, 1], vec![vec![3]])], + ), + ] { + let node_challenge = challenge(&[(2, &picked)]); + let opening = node.open(&node_challenge).unwrap(); + verify_paths(&receipt, &node_challenge, &opening).unwrap(); + let runs = node.replayers[1].runs.borrow(); + // the turn's own replay comes first + let lineage = &runs[runs.len() - expected.len()..]; + assert_eq!(lineage, expected, "{picked:?}"); + } +} + +#[test] +fn a_prefix_another_sequence_computed_is_replayed_as_the_turns_own() { + let node = Node::new(); + // a cached prompt in sequence 3, shared with sequence 1 + node.record(ubatch(&[(3, 0), (3, 1), (3, 2)], &[0, 1, 2], true)); + for recorder in &node.stages { + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + } + node.record(ubatch(&[(1, 3), (1, 4)], &[3, 4], true)); + let receipt = node.commit(1, 3..5, 4); + let challenge = challenge(&[(0, &[2, 4]), (2, &[2, 4])]); + let opening = node.open(&challenge).unwrap(); + verify_shape(&receipt, MODEL_LAYERS).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + // the ubatch of sequence 3 runs as sequence 1, at its recorded cells + let steps = node.replayers[1].steps.borrow(); + let (record, capture) = decode(&steps[0]); + assert_eq!(record.seq, vec![1, 1, 1]); + assert_eq!(record.token, vec![1000, 1001, 1002]); + assert_eq!( + (&record.pos, &record.cell), + (&vec![0, 1, 2], &vec![0, 1, 2]) + ); + assert_eq!(capture, [2]); + assert!(node.replayers[1].seed.borrow().is_none()); +} + +#[test] +fn a_prefix_ubatch_replays_whole_with_the_columns_the_prefix_dropped() { + let node = Node::new(); + // the cache sequence computed five positions and kept three + let columns: Vec<(i32, i32)> = (0..5).map(|p| (3, p)).collect(); + node.record(ubatch(&columns, &[0, 1, 2, 3, 4], true)); + for recorder in &node.stages { + recorder.memory_op(MemoryOp::SeqRm, 3, -1, 3, -1); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, 0, 3); + } + node.record(ubatch(&[(1, 3)], &[9], true)); + let receipt = node.commit(1, 3..4, 3); + assert_eq!(receipt.stages[0].prefix.as_ref().unwrap().positions, 3); + let challenge = challenge(&[(3, &[1, 3])]); + let opening = node.open(&challenge).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + let steps = node.replayers[1].steps.borrow(); + let (record, capture) = decode(&steps[0]); + assert_eq!(record.pos, vec![0, 1, 2, 3, 4]); + assert_eq!(record.seq, vec![1; 5]); + assert_eq!(capture, [1]); +} + +#[test] +fn a_column_of_the_turns_own_sequence_in_a_prefix_ubatch_is_a_dummy() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // sequence 1 served another request when sequence 3 computed the cache + record( + &recorder, + ubatch(&[(1, 40), (3, 0), (3, 1)], &[9, 0, 1], true), + ); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + recorder.commit("r1", 1, TurnId::default(), 2..3).unwrap(); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[1, 2])]), &replayer) + .unwrap(); + let runs = replayer.runs.borrow(); + assert_eq!(runs.last().unwrap(), &(Vec::new(), vec![vec![1]])); + drop(runs); + let steps = replayer.steps.borrow(); + let (record, _) = decode(&steps[0]); + // the other request's column takes the writer's number, as a dummy + assert_eq!(record.seq, vec![3, 1, 1]); + assert_eq!(record.token, vec![DUMMY_TOKEN, 1000, 1001]); + assert_eq!(record.pos, vec![0, 0, 1]); + assert_eq!(record.cell, vec![9, 0, 1]); + assert_eq!( + record.input.as_ref().unwrap().rows, + vec![0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7] + ); +} + +#[test] +fn a_prefix_replay_that_diverges_is_anchored_to_the_committed_values() { + let (node, receipt) = continued_turn(); + let mut replayer = FakeReplayer::for_stage(1); + replayer.fused = true; + let challenge = challenge(&[(2, &[1, 4])]); + let opened = node.stages[1].open(&challenge, &replayer).unwrap(); + // each scope replays the turn and the prefix's ubatch + assert_eq!( + *replayer.scopes.borrow(), + [ + "full", + "full", + "committed", + "committed", + "anchored", + "anchored" + ] + ); + let anchors = replayer.anchors.borrow(); + assert!(anchors.iter().any(|a| a.pos == 1 && a.seq == 7)); + let (fresh, _) = continued_turn(); + let honest = FakeReplayer::for_stage(1); + assert_eq!(opened, fresh.stages[1].open(&challenge, &honest).unwrap()); + drop(receipt); +} + +#[test] +fn a_replay_that_does_not_reproduce_the_prefix_is_refused() { + let (node, _) = continued_turn(); + let mut replayer = FakeReplayer::for_stage(1); + replayer.corrupt = true; + let error = node.stages[1] + .open(&challenge(&[(2, &[1, 4])]), &replayer) + .unwrap_err(); + assert!( + format!("{error:#}").contains("replay diverged"), + "{error:#}" + ); +} + +#[test] +fn a_prefix_cell_a_later_request_wrote_cannot_be_opened() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(3, 0), (3, 1)], &[0, 1], true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + recorder.commit("r1", 1, TurnId::default(), 2..3).unwrap(); + // both sequences end, and another request takes the cell of position 1 + recorder.memory_op(MemoryOp::SeqRm, 3, -1, -1, -1); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + record(&recorder, ubatch(&[(5, 0)], &[1], true)); + let replayer = FakeReplayer::for_stage(1); + let error = recorder + .open(&challenge(&[(2, &[1, 2])]), &replayer) + .unwrap_err(); + let cannot = error.downcast_ref::().expect("a cannot-open"); + assert_eq!(cannot.reason, CannotOpenReason::CellsOverwritten); + assert_eq!(cannot.receipt_id, "r1"); + assert_eq!(replayer.replays.get(), 0); +} + +/// Why a turn of sequence 1 at position `at` cannot be committed. +fn refused(recorder: &Recorder, at: i32) -> String { + record(recorder, ubatch(&[(1, at)], &[20], true)); + let at = u32::try_from(at).unwrap(); + let error = recorder + .commit("r", 1, TurnId::default(), at..at + 1) + .unwrap_err(); + format!("{error:#}") +} + +#[test] +fn a_turn_whose_prefix_cannot_be_replayed_gets_no_receipt() { + let cached = || { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r0", 1, TurnId::default(), 0..2).unwrap(); + recorder + }; + // nothing in the way: the turn commits its prefix + let recorder = cached(); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + recorder.commit("r", 1, TurnId::default(), 2..3).unwrap(); + + // a state load: the rows the turn reads were computed elsewhere + let recorder = cached(); + recorder.memory_op(MemoryOp::StateRead, 1, -1, -1, -1); + assert!(refused(&recorder, 2).contains("cached prefix is unknown")); + + // a compaction moved every cell + let recorder = cached(); + recorder.memory_op(MemoryOp::Compact, -1, -1, -1, -1); + assert!(refused(&recorder, 2).contains("cached prefix is unknown")); + + // a ubatch the recorder could not record computed position 2 + let recorder = cached(); + recorder.unrecorded_ubatch("a ubatch of embeddings"); + let message = refused(&recorder, 3); + assert!(message.contains("cached prefix is unknown"), "{message}"); + assert!(message.contains("position 2"), "{message}"); + + // cells of two requests + let recorder = cached(); + record( + &recorder, + ubatch(&[(2, 0), (2, 1), (2, 2)], &[10, 11, 12], true), + ); + recorder.memory_op(MemoryOp::SeqCp, 2, 1, 2, 3); + let message = refused(&recorder, 3); + assert!(message.contains("cannot follow"), "{message}"); +} + +#[test] +fn a_prefix_past_the_input_budget_gets_no_receipt() { + // a stage after the first keeps 4 bytes of input per token; the second + // ubatch is past the budget, so the first goes + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu").with_lineage_input_bytes(12); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + record(&recorder, ubatch(&[(1, 2), (1, 3)], &[2, 3], true)); + recorder.commit("r0", 1, TurnId::default(), 0..4).unwrap(); + let message = refused(&recorder, 4); + assert!(message.contains("no longer held"), "{message}"); + + // a ubatch dropped while the turn ran: the turn read the prefix, but + // the stage could not open it, so it commits nothing + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu").with_lineage_input_bytes(12); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r0", 1, TurnId::default(), 0..2).unwrap(); + record(&recorder, ubatch(&[(1, 2), (1, 3)], &[2, 3], true)); + let error = recorder + .commit("r", 1, TurnId::default(), 2..4) + .unwrap_err(); + assert!(format!("{error:#}").contains("no longer held"), "{error:#}"); + // a first stage keeps no input rows, so nothing is dropped + let first = Recorder::new(0, STAGES[0].clone(), "cpu").with_lineage_input_bytes(0); + let stage = Stage::new(0); + let mut prompt = ubatch(&[(1, 0), (1, 1)], &[0, 1], true); + prompt.input = None; + record_on(&first, &stage, prompt); + first.commit("r0", 1, TurnId::default(), 0..2).unwrap(); + let mut next = ubatch(&[(1, 2)], &[2], true); + next.input = None; + record_on(&first, &stage, next); + let commitment = first.commit("r", 1, TurnId::default(), 2..3).unwrap(); + assert!(commitment.prefix.unwrap().tokens.is_some()); +} + +#[test] +fn a_hybrid_stage_gives_no_receipt_for_a_cached_prefix() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.set_recurrent(true); + recorder.record_state(1, Some(b"state at 0")); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r0", 1, TurnId::default(), 0..2).unwrap(); + recorder.record_state(1, Some(b"state at 2")); + let message = refused(&recorder, 2); + assert!(message.contains("recurrent state"), "{message}"); +} + +#[test] +fn a_stage_admits_only_the_prefix_positions_a_draw_picks() { + let (node, _) = continued_turn(); + let recorder = &node.stages[1]; + recorder + .check_challenge(&challenge(&[(2, &[0, 2, 3, 4]), (3, &[0, 2, 4])])) + .unwrap(); + let mut head = challenge(&[(2, &[1, 4])]); + head.head = vec![1]; + for refused in [ + // three positions of the prefix + challenge(&[(2, &[0, 1, 2, 4])]), + // other positions in one layer than in the other + challenge(&[(2, &[0, 4]), (3, &[1, 4])]), + // no position of the turn + challenge(&[(2, &[0, 1])]), + // a head position in the prefix + head, + ] { + assert!( + recorder.check_challenge(&refused).is_err(), + "admitted {refused:?}" + ); + } +} diff --git a/crates/skippy-receipts/src/recorder/recurrent.rs b/crates/skippy-receipts/src/recorder/recurrent.rs new file mode 100644 index 00000000..83ca7862 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/recurrent.rs @@ -0,0 +1,85 @@ +//! The recurrent state each turn of a hybrid model starts from. +//! +//! A recurrent layer (the gated delta net, Mamba) keeps one state per +//! sequence that every ubatch overwrites, so a replay cannot rebuild the +//! state a turn started from out of the stage's cache, as it does an +//! attention layer's KV cells. The native recorder exports the state before +//! a turn's first ubatch. The stage commits its digest with the turn and +//! keeps the bytes while a client can challenge the turn, and a replay +//! starts from them. A state is tens of megabytes for a hybrid model of a +//! few billion parameters, so a turn no client can challenge drops it at +//! once. + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::Instant; + +use super::{Recorder, RecorderState}; +use crate::commitment::{Hash, recurrent_state_digest}; + +/// The state a turn started from: its digest, and its bytes while the +/// turn can still be opened. +#[derive(Clone, Debug)] +pub(super) struct TurnState { + pub digest: Hash, + pub bytes: Option>, +} + +impl TurnState { + fn new(state: &[u8]) -> Self { + Self { + digest: recurrent_state_digest(state), + bytes: Some(Arc::from(state)), + } + } + + pub(super) fn bytes_held(&self) -> usize { + self.bytes.as_ref().map_or(0, |bytes| bytes.len()) + } +} + +impl Recorder { + /// Marks the stage as one with hybrid memory: each turn must start from + /// a reported recurrent state ([`Self::record_state`]). + pub fn set_recurrent(&self, recurrent: bool) { + self.recurrent.store(recurrent, Ordering::Relaxed); + } + + /// Whether the stage keeps recurrent state ([`Self::set_recurrent`]). + /// A turn that continues a cached prefix of such a stage gets no + /// receipt: the state it started from is not recorded. + pub fn is_recurrent(&self) -> bool { + self.recurrent.load(Ordering::Relaxed) + } + + /// The recurrent state the next turn of `seq` starts from, or `None` + /// when the stage could not read it. A report for a turn already under + /// way is ignored: the turn keeps the state it started from. + pub fn record_state(&self, seq: i32, state: Option<&[u8]>) { + let state = state.map(TurnState::new); + let mut guard = self.lock(); + let log = &mut guard.seqs.entry(seq).or_default().live; + if log.prefix.is_some() { + return; + } + log.state = Some(state.ok_or_else(|| "the stage could not read it".to_string())); + } +} + +impl RecorderState { + /// Drops the state bytes of committed turns no client can still + /// challenge. + pub(super) fn drop_unpinned_states(&mut self, now: Instant) { + for turn in &mut self.committed { + if turn.pin.holds(now) { + continue; + } + if let Some(state) = turn.state.as_mut() { + let held = state.bytes_held(); + state.bytes = None; + turn.bytes -= held; + self.committed_bytes -= held; + } + } + } +} diff --git a/crates/skippy-receipts/src/recorder/recurrent_opening.rs b/crates/skippy-receipts/src/recorder/recurrent_opening.rs new file mode 100644 index 00000000..4652df33 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/recurrent_opening.rs @@ -0,0 +1,146 @@ +//! A stage's side of the recurrent check: the ubatch that computed an +//! attention pick in a layer whose token mixing reads a recurrent state +//! (the gated delta net, Mamba's scan, a short convolution). +//! +//! Such a layer has no KV rows to open: each ubatch continues one state per +//! sequence, which it reads before its tokens and writes after them. The +//! stage commits the state each ubatch read in the mixing leaf of its first +//! position. For the first such pick of a challenge, it opens the mixing +//! leaves of the pick's whole ubatch, and of the position after it, whose +//! state is the one the ubatch left. The replay that opens the picked +//! layers reports them, mixing values alone. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use anyhow::{Context, Result, ensure}; + +use super::CommittedTurn; +use super::event_log::{Event, Written}; +use super::stage_opening::{Divergence, ReplayPlan, Replayed, computing_step}; +use crate::attention::opening::AttentionPick; +use crate::commitment::{mixing_leaf, mixing_slot}; +use crate::wire::{MixingLeafOpening, RecurrentOpening, mixing_bytes, mixing_values}; + +/// The ubatch an attention pick was computed in, on a layer that reads a +/// recurrent state. +pub(super) struct RegionPlan { + pub position: u32, + pub layer: u32, + /// The ubatch's positions of the turn's sequence. + pub start: u32, + pub end: u32, + /// The turn goes on past the ubatch, so the leaf at `end` holds the + /// state the ubatch left. + pub continues: bool, + /// By replay step, the positions whose mixing values the opening shows. + pub mixing: BTreeMap>, +} + +impl RegionPlan { + /// Every position the opening shows a mixing leaf of. + pub fn positions(&self) -> Range { + self.start..self.end + u32::from(self.continues) + } +} + +/// The region of the first attention pick of `picks` in `layers` on a layer +/// of `state_layers`, if there is one. +pub(super) fn region_plan( + turn: &CommittedTurn, + written: &BTreeMap, + picks: &[AttentionPick], + layers: &Range, + state_layers: &BTreeSet, +) -> Result> { + let Some(pick) = picks + .iter() + .find(|p| layers.contains(&p.layer) && state_layers.contains(&p.layer)) + else { + return Ok(None); + }; + let step = computing_step(written, pick.position)?; + let Event::Ubatch(record) = &turn.events[step] else { + unreachable!("a computing step is a ubatch"); + }; + let positions = record + .seq + .iter() + .zip(&record.pos) + .filter(|(seq, _)| **seq == turn.seq) + .map(|(_, &pos)| u32::try_from(pos)) + .collect::, _>>()?; + let (start, end) = match (positions.first(), positions.last()) { + (Some(&first), Some(&last)) => (first, last + 1), + _ => unreachable!("the ubatch computed the pick"), + }; + ensure!( + (end - start) as usize == positions.len(), + "the ubatch that computed position {} skips positions", + pick.position + ); + ensure!( + start >= turn.position_start, + "the ubatch that computed position {} began before the turn", + pick.position + ); + let mut mixing = BTreeMap::new(); + mixing.insert(step, (start..end).collect::>()); + let continues = end < turn.position_end; + if continues { + mixing + .entry(computing_step(written, end)?) + .or_insert_with(Vec::new) + .push(end); + } + Ok(Some(RegionPlan { + position: pick.position, + layer: pick.layer, + start, + end, + continues, + mixing, + })) +} + +/// The opening of the plan's region, checked against the committed leaves. +pub(super) fn open_region( + plan: &ReplayPlan, + replayed: &Replayed, + layer_start: u32, +) -> Result> { + let Some(region) = &plan.region else { + return Ok(Vec::new()); + }; + let layer = region.layer; + let leaves = region + .positions() + .map(|position| { + let values = replayed.get(&(position, layer)).with_context(|| { + format!("replay did not report the mixing of position {position}, layer {layer}") + })?; + let mixing = values.mixing_openings(); + let decoded = mixing_bytes(&mixing)?; + let committed = plan.committed(position, mixing_slot(layer, layer_start))?; + if mixing_leaf(position, layer, &mixing_values(&decoded)) != committed.hash { + return Err(Divergence(format!( + "replay diverged from the committed mixing leaf at position {position}, \ + layer {layer}" + )) + .into()); + } + Ok(MixingLeafOpening { + position, + mixing, + path: committed.path.clone(), + }) + }) + .collect::>()?; + Ok(vec![RecurrentOpening { + position: region.position, + layer, + start: region.start, + end: region.end, + leaves, + }]) +} diff --git a/crates/skippy-receipts/src/recorder/recurrent_tests.rs b/crates/skippy-receipts/src/recorder/recurrent_tests.rs new file mode 100644 index 00000000..41815f7c --- /dev/null +++ b/crates/skippy-receipts/src/recorder/recurrent_tests.rs @@ -0,0 +1,206 @@ +//! The recurrent state a turn of a hybrid model starts from, on the test +//! model of `tests.rs`. + +use super::*; +use crate::attention::opening::AttentionPick; +use crate::commitment::recurrent_state_digest; +use crate::recurrent::verify_region; +use crate::wire::{MixingKind, MixingLeafOpening, TensorOpening}; + +fn hybrid() -> Recorder { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.set_recurrent(true); + recorder +} + +/// A turn of three positions in two ubatches, from `state`. +fn turn(recorder: &Recorder, state: &[u8]) -> StageCommitment { + recorder.record_state(1, Some(state)); + record(recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + record(recorder, ubatch(&[(1, 2)], &[2], true)); + recorder.commit("r1", 1, TurnId::default(), 0..3).unwrap() +} + +#[test] +fn a_hybrid_turn_commits_its_state_and_replays_from_it() { + let recorder = hybrid(); + let commitment = turn(&recorder, b"state at 0"); + assert_eq!( + commitment.recurrent_state, + Some(hex::encode(recurrent_state_digest(b"state at 0"))) + ); + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge(&[(2, &[2])]), &replayer).unwrap(); + // the turn's own cells hold position 0 and 1, but the recurrent state + // is known only at the turn's start, so every ubatch is replayed + assert_eq!(replayer.steps.borrow().len(), 2); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + assert!(seed.cells.is_empty()); + assert_eq!(seed.state.as_deref(), Some(&b"state at 0"[..])); +} + +#[test] +fn a_hybrid_turn_without_its_state_is_not_committed() { + let recorder = hybrid(); + record(&recorder, ubatch(&[(1, 0)], &[0], true)); + let error = recorder + .commit("r1", 1, TurnId::default(), 0..1) + .unwrap_err(); + assert!( + format!("{error:#}").contains("no recurrent state"), + "{error:#}" + ); + + recorder.record_state(1, None); + record(&recorder, ubatch(&[(1, 1)], &[1], true)); + let error = recorder + .commit("r2", 1, TurnId::default(), 1..2) + .unwrap_err(); + assert!(format!("{error:#}").contains("could not read"), "{error:#}"); +} + +#[test] +fn a_state_reported_mid_turn_is_ignored() { + let recorder = hybrid(); + recorder.record_state(1, Some(b"start")); + record(&recorder, ubatch(&[(1, 0)], &[0], true)); + recorder.record_state(1, Some(b"later")); + record(&recorder, ubatch(&[(1, 1)], &[1], true)); + let commitment = recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + assert_eq!( + commitment.recurrent_state, + Some(hex::encode(recurrent_state_digest(b"start"))) + ); +} + +#[test] +fn removing_a_sequence_drops_the_state_of_its_next_turn() { + let recorder = hybrid(); + recorder.record_state(1, Some(b"stale")); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + record(&recorder, ubatch(&[(1, 0)], &[0], true)); + assert!(recorder.commit("r1", 1, TurnId::default(), 0..1).is_err()); +} + +#[test] +fn a_turn_no_client_can_challenge_drops_its_state() { + let recorder = hybrid(); + turn(&recorder, &[7; 1000]); + recorder.release_pin("r1"); + let replayer = FakeReplayer::for_stage(1); + let error = recorder + .open(&challenge(&[(2, &[2])]), &replayer) + .unwrap_err(); + assert!(format!("{error:#}").contains("no longer held"), "{error:#}"); + let state = recorder.lock(); + assert_eq!(state.committed_bytes, state.committed[0].bytes); + assert!( + state.committed[0] + .state + .as_ref() + .is_some_and(|s| s.bytes.is_none()) + ); +} + +#[test] +fn a_stage_without_hybrid_memory_commits_no_state() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let commitment = turn(&recorder, b"ignored"); + assert!(commitment.recurrent_state.is_none()); +} + +/// A stage whose layer 2 reads a recurrent state, over a prompt of three +/// positions and two decode steps. +fn region_turn() -> (Recorder, FakeReplayer, Receipt) { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let mut stage = Stage::new(1); + stage.state_layers = vec![2]; + for record in [ + ubatch(&[(1, 0), (1, 1), (1, 2)], &[0, 1, 2], true), + ubatch(&[(1, 3)], &[3], true), + ubatch(&[(1, 4)], &[4], true), + ] { + record_on(&recorder, &stage, record); + } + let receipt = Receipt { + version: RECEIPT_VERSION, + receipt_id: "r1".into(), + model: "m".into(), + position_start: 0, + position_end: 5, + tokens: recorder.turn_tokens("r1").unwrap_or_default(), + generation_start: 2, + final_token: None, + stages: vec![recorder.commit("r1", 1, TurnId::default(), 0..5).unwrap()], + binding: None, + }; + (recorder, FakeReplayer::new(stage), receipt) +} + +fn attention_at(position: u32, layer: u32) -> Challenge { + let mut challenge = challenge(&[(layer, &[position])]); + challenge.attention = vec![AttentionPick { + position, + layer, + head_draw: 0, + }]; + challenge +} + +fn state_opened(leaf: &MixingLeafOpening) -> bool { + leaf.mixing + .iter() + .any(|t| t.kind == MixingKind::State && t.values.is_some()) +} + +#[test] +fn a_pick_on_a_state_layer_opens_its_ubatch_and_the_state_it_left() { + let (recorder, replayer, receipt) = region_turn(); + let challenge = attention_at(1, 2); + let opening = recorder.open(&challenge, &replayer).unwrap(); + let region = &opening.recurrent[0]; + assert_eq!((region.start, region.end), (0, 3)); + let positions: Vec = region.leaves.iter().map(|l| l.position).collect(); + assert_eq!(positions, vec![0, 1, 2, 3]); + let opened: Vec = region.leaves.iter().map(state_opened).collect(); + assert_eq!(opened, vec![true, false, false, true]); + // every ubatch is replayed, so the state is the one the turn computed + assert_eq!(*replayer.scopes.borrow(), vec!["full"]); + verify_region(&receipt, &challenge.attention[0], region).unwrap(); + + // a state the stage did not commit no longer hashes to its leaf + let mut forged = region.clone(); + let state = forged.leaves[3] + .mixing + .iter_mut() + .find(|t| t.kind == MixingKind::State) + .unwrap(); + let mut bytes = state.bytes().unwrap().unwrap(); + bytes[0] ^= 1; + *state = TensorOpening::new(MixingKind::State, 0, Some((GGML_F32, &bytes))); + assert!(verify_region(&receipt, &challenge.attention[0], &forged).is_err()); + + // nor does a region that leaves out the state it left + let mut short = region.clone(); + short.leaves.pop(); + assert!(verify_region(&receipt, &challenge.attention[0], &short).is_err()); +} + +#[test] +fn the_last_ubatch_of_a_turn_opens_no_state_after_it() { + let (recorder, replayer, receipt) = region_turn(); + let challenge = attention_at(4, 2); + let opening = recorder.open(&challenge, &replayer).unwrap(); + let region = &opening.recurrent[0]; + assert_eq!((region.start, region.end), (4, 5)); + assert_eq!(region.leaves.len(), 1); + assert!(state_opened(®ion.leaves[0])); + verify_region(&receipt, &challenge.attention[0], region).unwrap(); +} + +#[test] +fn a_pick_on_an_attention_layer_opens_no_region() { + let (recorder, replayer, _) = region_turn(); + let opening = recorder.open(&attention_at(1, 3), &replayer).unwrap(); + assert!(opening.recurrent.is_empty()); +} diff --git a/crates/skippy-receipts/src/recorder/replay.rs b/crates/skippy-receipts/src/recorder/replay.rs new file mode 100644 index 00000000..339936e1 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/replay.rs @@ -0,0 +1,313 @@ +//! What a replay of a recorded turn is given and what it reports: the steps +//! and the cells it starts from, the values it recomputes per position and +//! layer, and the [`Replayer`] a stage implements over its native runtime. + +use std::sync::Arc; + +use anyhow::{Context, Result, bail}; + +use super::{KvCell, PrefixCell, UbatchRecord}; +use crate::attention::AttentionDescriptor; +use crate::layer_tensors::{FLAG_ROUTER, GGML_F32, MIXING_KINDS, TensorKind, UbatchColumns}; +use crate::wire::{MatrixOpening, MixingKind, SelectionOpening, TensorOpening, encode_bytes}; + +/// One step of a replay, columns ready for the native side. Other +/// sequences' columns are dummies at their recorded cells. +#[derive(Clone, Debug, PartialEq)] +pub enum ReplayStep { + Decode { + record: Arc, + /// Positions of the replayed sequence to capture at this step. + capture: Vec, + /// Positions of the replayed sequence whose token-mixing values + /// alone to capture at this step, besides `capture`. + mixing: Vec, + }, + /// Removes positions `[p0, p1)` of the replayed sequence; `p1 < 0` has no end. + SeqRm { p0: i32, p1: i32 }, +} + +/// One position of the challenged layer, as the replay recomputed it. +#[derive(Clone, Debug, PartialEq)] +pub struct ReplayedLayer { + /// Little-endian f32 bytes. + pub residual_in: Vec, + pub residual_out: Option>, + /// The logits a final stage's last layer leads to, little-endian f32, + /// where the replay reported them. + pub logits: Option>, + /// The mixing leaf's values, in leaf order. + pub mixing: Vec, + pub matmuls: Vec, + pub selections: Vec, + /// The layer's attention ops, as the replay's graph describes them. + pub attention: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ReplayedMixing { + pub kind: MixingKind, + pub index: u32, + /// ggml type and bytes; `None` where the layer kept no row. + pub value: Option<(i32, Vec)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ReplayedMatmul { + pub index: u32, + pub weight: String, + pub router: bool, + pub experts: Option>, + /// Little-endian f32 bytes. + pub input: Vec, + pub output: Vec, +} + +impl ReplayedLayer { + /// The token-mixing values alone of column `col` of a captured replay + /// ubatch for `layer`. + pub fn from_mixing_columns(layer: u32, columns: &dyn UbatchColumns, col: usize) -> Self { + Self { + residual_in: Vec::new(), + residual_out: None, + logits: None, + mixing: mixing_columns(layer, columns, col), + matmuls: Vec::new(), + selections: Vec::new(), + attention: Vec::new(), + } + } + + /// Collects column `col` of a captured replay ubatch for `layer`. + pub fn from_columns(layer: u32, columns: &dyn UbatchColumns, col: usize) -> Result { + let f32_column = |l: u32, kind: TensorKind, index: u32| -> Result>> { + match columns.column(l, kind, index, col) { + Some(c) if c.ggml_type != GGML_F32 => { + bail!( + "replay reported {} {index} of layer {l} as type {}", + kind.name(), + c.ggml_type + ) + } + c => Ok(c.map(|c| c.bytes.to_vec())), + } + }; + let residual_in = f32_column(layer, TensorKind::Residual, 0)? + .with_context(|| format!("replay did not capture the residual of layer {layer}"))?; + let residual_out = f32_column(layer + 1, TensorKind::Residual, 0)?; + let logits = f32_column(layer + 1, TensorKind::Logits, 0)?; + let mixing = mixing_columns(layer, columns, col); + let mut matmuls = Vec::new(); + for index in 0..columns.count(layer, TensorKind::MatmulInput) { + let (Some(input), Some(output)) = ( + columns.column(layer, TensorKind::MatmulInput, index, col), + f32_column(layer, TensorKind::MatmulOutput, index)?, + ) else { + // the layer dropped this position's row before the matmul + continue; + }; + if input.ggml_type != GGML_F32 { + bail!( + "replay reported matmul input {index} of layer {layer} as type {}", + input.ggml_type + ); + } + let experts = columns + .column(layer, TensorKind::ExpertIds, index, col) + .map(|c| c.i32_values().context("expert ids are not i32")) + .transpose()?; + matmuls.push(ReplayedMatmul { + index, + weight: input.name.to_owned(), + router: input.flags & FLAG_ROUTER != 0, + experts, + input: input.bytes.to_vec(), + output, + }); + } + let selections = (0..columns.count(layer, TensorKind::Selection)) + .filter_map(|index| { + let column = columns.column(layer, TensorKind::Selection, index, col)?; + Some( + column + .i32_values() + .context("a selection is not i32") + .map(|ids| SelectionOpening { index, ids }), + ) + }) + .collect::>()?; + Ok(Self { + residual_in, + residual_out, + logits, + mixing, + matmuls, + selections, + attention: Vec::new(), + }) + } + + pub(super) fn mixing_openings(&self) -> Vec { + self.mixing + .iter() + .map(|m| { + TensorOpening::new( + m.kind, + m.index, + m.value.as_ref().map(|(t, bytes)| (*t, bytes.as_slice())), + ) + }) + .collect() + } + + pub(super) fn matrices(&self) -> Vec { + self.matmuls + .iter() + .map(|m| MatrixOpening { + index: m.index, + weight: m.weight.clone(), + router: m.router, + experts: m.experts.clone(), + input: encode_bytes(&m.input), + output: encode_bytes(&m.output), + }) + .collect() + } +} + +/// The mixing leaf's values of `layer` in column `col`, in leaf order. +fn mixing_columns(layer: u32, columns: &dyn UbatchColumns, col: usize) -> Vec { + MIXING_KINDS + .iter() + .flat_map(|&kind| (0..columns.count(layer, kind)).map(move |index| (kind, index))) + .map(|(kind, index)| ReplayedMixing { + kind: MixingKind::from_tensor_kind(kind).expect("a mixing kind"), + index, + value: columns + .column(layer, kind, index, col) + .map(|c| (c.ggml_type, c.bytes.to_vec())), + }) + .collect() +} + +/// One position of one layer, as a replay recomputed it. +pub type ReplayedPosition = (u32, u32, ReplayedLayer); + +/// The cells of the stage's KV cache a replay starts from, copied into the +/// replay context before its steps: the prefix the turn attended to, and +/// the turn's own cells when the replay computes only some of its ubatches +/// (`turn_seed`). +#[derive(Clone, Debug, PartialEq)] +pub struct ReplaySeed { + pub cells: Vec, + /// KV cells the replay context needs: the seeded ones and every one + /// the steps use. + pub n_cells: u32, + /// On a stage with hybrid memory, the recurrent state the turn started + /// from, which the replay imports after the cells. + pub state: Option>, +} + +impl ReplaySeed { + pub fn indices(&self) -> Vec { + self.cells.iter().map(|c| c.cell).collect() + } + + pub fn positions(&self) -> Vec { + self.cells.iter().map(|c| c.pos).collect() + } +} + +/// Which tensors a replay reports, and from which values. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ReplayScope<'a> { + /// The committed values and the matmuls and selections an opening + /// shows besides them. + Full, + /// The committed values alone, as the live recorder marks them. Marking + /// more can change which kernels a backend fuses (CUDA's fused MoE + /// routing and gated matmuls, for two), so a full replay may not + /// reproduce the committed values bit for bit while this one does. + Committed, + /// As [`Self::Full`], with each anchor's committed value written into + /// its token's column as soon as the replay computes it, so the matmuls + /// and selections of the anchored tokens follow from the committed + /// values. + Anchored(&'a [ReplayAnchor]), +} + +/// A committed value an anchored replay writes into one token's column. +#[derive(Clone, Debug, PartialEq)] +pub struct ReplayAnchor { + /// The decode step, as an index into the replay's steps. + pub step: usize, + pub seq: i32, + pub pos: i32, + pub layer: u32, + pub value: AnchorValue, + pub values: Vec, +} + +/// What an anchor replaces. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AnchorValue { + /// The residual entering the layer. + Residual, + /// A token-mixing output, by index. + MixingOutput(u32), +} + +/// Replays a sequence's recorded ubatches; implemented over the native runtime. +pub trait Replayer { + /// Runs `steps` for `seq`, from the cells of `seed` when there is one, + /// and returns, for every captured position and every one of `layers`, + /// the position, the layer and its values. A seed is copied with the + /// stage idle, after [`super::Recorder::check_seed`] confirms its cells still + /// hold what the turn read or wrote. `scope` says which tensors it + /// reports. + fn replay( + &self, + seq: i32, + layers: &[u32], + scope: ReplayScope<'_>, + seed: Option<&ReplaySeed>, + steps: &[ReplayStep], + ) -> Result>; + + /// The rows the stage stored for `layer` in `cells`, read from its KV + /// cache with the stage idle, after [`super::Recorder::check_cells`] confirms + /// they still hold what the turn read or wrote. One [`StoredRows`] per + /// stored row of the layer, by index, each with a row per cell. + fn read_rows(&self, layer: u32, cells: &[PrefixCell]) -> Result>; + + /// [`Self::read_rows`] of cells whose rows are about to be checked + /// against their digests ([`super::Recorder::verify_exposed`]): a cell + /// the recorder marked exposed is read too, after + /// [`super::Recorder::check_unseen_overwrite`]. + fn read_rows_to_check(&self, layer: u32, cells: &[PrefixCell]) -> Result> { + self.read_rows(layer, cells) + } + + /// Pins `cells` of the stage's KV cache in place of those pinned before + /// ([`super::Recorder::pinned_cells`]): while one is empty, the stage writes + /// other cells as long as a ubatch fits there. It does not wait for the + /// stage to be idle. + fn pin_cells(&self, cells: &[KvCell]) -> Result<()>; +} + +/// One stored row of a layer in several KV cells, in the cache's type. +#[derive(Clone, Debug, PartialEq)] +pub struct StoredRows { + pub ggml_type: i32, + pub row_bytes: usize, + /// Row `i` at `values[i * row_bytes..]`. + pub values: Vec, +} + +impl StoredRows { + pub fn row(&self, i: usize) -> &[u8] { + self.values + .get(i * self.row_bytes..(i + 1) * self.row_bytes) + .unwrap_or(&[]) + } +} diff --git a/crates/skippy-receipts/src/recorder/stage_opening.rs b/crates/skippy-receipts/src/recorder/stage_opening.rs new file mode 100644 index 00000000..ffc80e35 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/stage_opening.rs @@ -0,0 +1,885 @@ +//! Opens a challenge on one stage: the picked layers it holds, the input of +//! layer 0 when it holds layer 0, the residual the output head reads when +//! it holds the final layer, and the residual leaves at its boundaries. +//! Picked layers, the layer-0 input and the head residual are recomputed by +//! one replay of the turn; boundary leaves come from the committed tree. +//! When that replay does not reproduce a committed leaf, one that reports +//! the committed values alone supplies them ([`ReplayScope::Committed`]), +//! and a full one anchored to them the matmuls and selections +//! ([`ReplayScope::Anchored`]). +//! +//! A challenge may pick positions of the turn's cached prefix. The stage +//! did not compute those in the turn: it opens each by replaying the one +//! recorded ubatch that wrote the position's cell, from a copy of the +//! prefix cells below that ubatch ([`super::prefix_opening`]). A replayed +//! leaf of such a position is checked against the leaves the stage +//! committed when it computed the position, and opens without a path. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use anyhow::{Context, Result, bail}; + +use super::cells::CellRecord; +use super::event_log::{Event, Written, last_writes}; +use super::prefix_opening::{PrefixPlan, lineage_replays}; +use super::recurrent_opening::{RegionPlan, open_region, region_plan}; +use super::turn_seed::Segment; +use super::{ + AnchorValue, CommittedTurn, DUMMY_TOKEN, MAX_REPLAYS_PER_RECEIPT, PrefixCell, Recorder, + ReplayAnchor, ReplayScope, ReplaySeed, ReplayStep, ReplayedLayer, UbatchRecord, turn, +}; +use crate::commitment::{ + Hash, encode_path, leaf_index, mixing_leaf, mixing_slot, residual_leaf, residual_slot, +}; +use crate::layer_tensors::{GGML_F32, decode_f32_bytes}; +use crate::wire::{ + AnchorOpening, BoundaryLeaf, CannotOpen, CannotOpenReason, Challenge, HeadOpening, + LayerOpening, LeafOpening, MixingKind, RecurrentOpening, StageOpening, encode_bytes, + mixing_bytes, mixing_values, +}; + +/// A leaf of the committed tree and its Merkle path. +pub(super) struct Committed { + pub(super) hash: Hash, + pub(super) path: Vec, +} + +/// One replay of the plan: the cells it starts from, and its steps. +pub(super) struct Replay { + pub(super) seed: Option, + pub(super) steps: Vec, +} + +/// What a replay must reproduce, and the replays that reproduce it. +pub(super) struct ReplayPlan { + seq: i32, + replays: Vec, + /// Layers to capture, sorted. + layers: Vec, + /// Token per opened position. + tokens: BTreeMap, + /// By (position, slot): the committed leaf. + leaves: BTreeMap<(u32, u64), Committed>, + /// The recurrent ubatch the opening shows. + pub(super) region: Option, + /// The picked positions of the turn's cached prefix. + prefix: Option, + /// The tokens of the turn's cached prefix, on the stage that holds + /// layer 0. + prefix_tokens: Vec, +} + +/// Replayed values by (position, layer). +pub(super) type Replayed = BTreeMap<(u32, u32), ReplayedLayer>; + +/// What a stage opens from one replay of the plan. +struct Opened { + layers: Vec, + anchors: Vec, + head: Vec, + recurrent: Vec, +} + +/// A replay that does not reproduce a committed leaf. +#[derive(Debug)] +pub(super) struct Divergence(pub(super) String); + +impl std::fmt::Display for Divergence { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Divergence {} + +fn replay_plan( + replayer: &dyn super::Replayer, + plan: &ReplayPlan, + scope: ReplayScope<'_>, +) -> Result { + let mut replayed = Replayed::new(); + for replay in &plan.replays { + let values = replayer.replay( + plan.seq, + &plan.layers, + scope, + replay.seed.as_ref(), + &replay.steps, + )?; + for (position, layer, values) in values { + replayed.insert((position, layer), values); + } + } + Ok(replayed) +} + +/// Replays the plan twice more: once for the committed values alone, then +/// in full from them. A backend that fused ops when serving computes them +/// apart in a full replay, so its matmuls drift from the committed values +/// layer after layer; anchored at every picked layer, they follow from the +/// committed values instead. +fn replay_anchored( + replayer: &dyn super::Replayer, + plan: &ReplayPlan, + imported: Option, +) -> Result { + let committed = replay_plan(replayer, plan, ReplayScope::Committed)?; + let mut anchored = Replayed::new(); + for replay in &plan.replays { + let anchors = anchors(plan, replay, &committed, imported)?; + let values = replayer.replay( + plan.seq, + &plan.layers, + ReplayScope::Anchored(&anchors), + replay.seed.as_ref(), + &replay.steps, + )?; + for (position, layer, values) in values { + anchored.insert((position, layer), values); + } + } + Ok(with_committed_values(anchored, committed)) +} + +/// The committed values a replay's captured tokens are anchored to: the +/// residual entering every replayed layer, except `imported`, whose input +/// the stage imports and the replay sets from the turn's own, and the +/// layer's token-mixing outputs. +fn anchors( + plan: &ReplayPlan, + replay: &Replay, + committed: &Replayed, + imported: Option, +) -> Result> { + let mut anchors = Vec::new(); + for (step, replay_step) in replay.steps.iter().enumerate() { + let ReplayStep::Decode { capture, .. } = replay_step else { + continue; + }; + for &position in capture { + let pos = i32::try_from(position)?; + for &layer in &plan.layers { + let values = committed.get(&(position, layer)).with_context(|| { + format!("the committed replay did not reach position {position}, layer {layer}") + })?; + let anchor = |value, values| ReplayAnchor { + step, + seq: plan.seq, + pos, + layer, + value, + values, + }; + if imported != Some(layer) { + anchors.push(anchor( + AnchorValue::Residual, + decode_f32_bytes(&values.residual_in), + )); + } + for mixing in values + .mixing + .iter() + .filter(|m| m.kind == MixingKind::Output) + { + if let Some((GGML_F32, bytes)) = &mixing.value { + anchors.push(anchor( + AnchorValue::MixingOutput(mixing.index), + decode_f32_bytes(bytes), + )); + } + } + } + } + } + Ok(anchors) +} + +/// An anchored replay's matmuls and selections with the committed values +/// of a replay at [`ReplayScope::Committed`]. +fn with_committed_values(mut full: Replayed, committed: Replayed) -> Replayed { + for (key, values) in committed { + if let Some(full) = full.get_mut(&key) { + full.residual_in = values.residual_in; + full.residual_out = values.residual_out; + full.logits = values.logits; + full.mixing = values.mixing; + } + } + full +} + +impl Recorder { + /// Opens this stage's part of a challenge, by replaying the turn unless + /// the same challenge was opened before. + pub fn open( + &self, + challenge: &Challenge, + replayer: &dyn super::Replayer, + ) -> Result { + let root = |committed: &_| turn(committed, &challenge.receipt_id).map(|t| t.tree.root()); + let opened_root = { + let mut state = self.lock(); + if let Some(opening) = state.openings.get(challenge) { + return Ok(StageOpening::clone(&opening)); + } + root(&state.committed) + }; + let opening = self + .open_uncached(challenge, replayer) + .map_err(|error| name_receipt(error, &challenge.receipt_id))?; + let opening = Arc::new(opening); + let mut state = self.lock(); + // a turn committed under the same id while this one replayed must + // not be answered with this opening + if opened_root.is_some() && root(&state.committed) == opened_root { + state.openings.insert(challenge.clone(), opening.clone()); + } + drop(state); + Ok(Arc::unwrap_or_clone(opening)) + } + + fn open_uncached( + &self, + challenge: &Challenge, + replayer: &dyn super::Replayer, + ) -> Result { + let positions = challenge.positions(); + if positions.is_empty() { + bail!("the challenge has no positions"); + } + let head = if self.holds_output { + challenge.head.clone() + } else { + Vec::new() + }; + let (plan, boundaries) = self.plan(challenge, &positions, &head)?; + let seeded: Vec = plan + .replays + .iter() + .filter_map(|replay| replay.seed.as_ref()) + .flat_map(|seed| seed.cells.iter().copied()) + .collect(); + self.verify_exposed(replayer, &seeded)?; + let mut replayed = replay_plan(replayer, &plan, ReplayScope::Full)?; + let opened = match self.open_replayed(challenge, &plan, &positions, &head, &replayed) { + Err(error) if error.is::() => { + let imported = (self.layers.start > 0).then_some(self.layers.start); + replayed = replay_anchored(replayer, &plan, imported)?; + self.open_replayed(challenge, &plan, &positions, &head, &replayed)? + } + opened => opened?, + }; + let Opened { + layers, + anchors, + head, + recurrent, + } = opened; + let attention = self.open_attention( + &challenge.receipt_id, + &challenge.attention, + &layers, + &replayed, + replayer, + )?; + let prefix = self.open_prefix(plan.prefix.as_ref(), replayer)?; + Ok(StageOpening { + stage_index: self.stage_index, + layers, + anchors, + entry: boundaries.entry, + exit: boundaries.exit, + head, + attention, + recurrent, + prefix, + prefix_tokens: plan.prefix_tokens, + }) + } + + /// Checks the replayed values against the committed leaves and opens + /// the picked layers, the anchors, the head and the recurrent region. + fn open_replayed( + &self, + challenge: &Challenge, + plan: &ReplayPlan, + positions: &[u32], + head: &[u32], + replayed: &Replayed, + ) -> Result { + let replayed_at = |position: u32, layer: u32| { + replayed + .get(&(position, layer)) + .with_context(|| format!("replay did not reach position {position}, layer {layer}")) + }; + let mut layers = Vec::new(); + for pick in challenge + .picks + .iter() + .filter(|p| self.layers.contains(&p.layer)) + { + let mut leaves = Vec::with_capacity(pick.positions.len()); + for &position in &pick.positions { + let values = replayed_at(position, pick.layer)?; + leaves.push(self.leaf_opening(plan, position, pick.layer, values)?); + } + layers.push(LayerOpening { + layer: pick.layer, + leaves, + }); + } + let mut anchors = Vec::new(); + if self.layers.start == 0 { + for &position in positions { + let values = replayed_at(position, 0)?; + let token = plan.tokens[&position]; + let committed = plan.committed(position, residual_slot(0, 0))?; + let leaf = residual_leaf(position, 0, Some(token), Some(&values.residual_in)); + if leaf != committed.hash { + return Err(Divergence(format!( + "replay diverged from the committed input of layer 0 at position {position}" + )) + .into()); + } + anchors.push(AnchorOpening { + position, + token, + residual: encode_bytes(&values.residual_in), + path: committed.path.clone(), + }); + } + } + let head = head + .iter() + .map(|&position| { + self.head_opening(plan, position, replayed_at(position, self.layers.end - 1)?) + }) + .collect::>()?; + Ok(Opened { + layers, + anchors, + head, + recurrent: open_region(plan, replayed, self.layers.start)?, + }) + } + + /// The residual leaving the final layer at a head position, checked + /// against its committed leaf. + fn head_opening( + &self, + plan: &ReplayPlan, + position: u32, + values: &ReplayedLayer, + ) -> Result { + let end = self.layers.end; + let residual = values + .residual_out + .as_deref() + .with_context(|| format!("position {position} is not an output row"))?; + let committed = plan.committed(position, residual_slot(end, self.layers.start))?; + if residual_leaf(position, end, None, Some(residual)) != committed.hash { + return Err(Divergence(format!( + "replay diverged from the committed output residual at position {position}" + )) + .into()); + } + Ok(HeadOpening { + position, + residual: encode_bytes(residual), + path: committed.path.clone(), + logits: values.logits.as_deref().map(encode_bytes), + }) + } + + /// Checks one replayed position of a picked layer against its committed + /// leaves and builds its opening. + fn leaf_opening( + &self, + plan: &ReplayPlan, + position: u32, + layer: u32, + values: &ReplayedLayer, + ) -> Result { + let start = self.layers.start; + let token = (layer == 0).then(|| plan.tokens[&position]); + let mixing = values.mixing_openings(); + let decoded = mixing_bytes(&mixing)?; + let recomputed = [ + ( + "residual-in", + residual_slot(layer, start), + residual_leaf(position, layer, token, Some(&values.residual_in)), + ), + ( + "mixing", + mixing_slot(layer, start), + mixing_leaf(position, layer, &mixing_values(&decoded)), + ), + ( + "residual-out", + residual_slot(layer + 1, start), + residual_leaf(position, layer + 1, None, values.residual_out.as_deref()), + ), + ]; + let mut paths = Vec::with_capacity(3); + for (name, slot, leaf) in recomputed { + let committed = plan.committed(position, slot)?; + if leaf != committed.hash { + return Err(Divergence(format!( + "replay diverged from the committed turn at position {position}, layer {layer}: \ + the {name} leaf differs" + )) + .into()); + } + paths.push(committed.path.clone()); + } + let [residual_in_path, mixing_path, residual_out_path] = + <[Vec; 3]>::try_from(paths).expect("three leaves"); + Ok(LeafOpening { + position, + residual_in: encode_bytes(&values.residual_in), + residual_out: values.residual_out.as_deref().map(encode_bytes), + residual_in_path, + mixing_path, + residual_out_path, + mixing, + matrices: values.matrices(), + selections: values.selections.clone(), + }) + } + + /// Finds the turn, collects the committed leaves the opening needs and + /// the replay steps. Counts a replay against the receipt when one is + /// needed. + fn plan( + &self, + challenge: &Challenge, + positions: &[u32], + head: &[u32], + ) -> Result<(ReplayPlan, Boundaries)> { + let start = self.layers.start; + let slots = self.slots(); + let mut layers: BTreeSet = challenge + .picks + .iter() + .map(|p| p.layer) + .filter(|layer| self.layers.contains(layer)) + .collect(); + if start == 0 { + // the input of layer 0 is opened at every picked position + layers.insert(0); + } + if !head.is_empty() { + // the head reads the residual leaving the final layer + layers.insert(self.layers.end - 1); + } + let mut guard = self.lock(); + let state = &mut *guard; + let turn = self.opening_turn_mut(&mut state.committed, &challenge.receipt_id)?; + // a picked position is one of the turn or of its prefix; a head + // position is one the turn sampled from, never one of the prefix + let in_turn = |p: &u32| (turn.position_start..turn.position_end).contains(p); + let in_prefix = |p: &u32| (*p as usize) < turn.prefix.len() && *p < turn.position_start; + if let Some(&position) = positions + .iter() + .find(|p| !in_turn(p) && !in_prefix(p)) + .or_else(|| head.iter().find(|p| !in_turn(p))) + { + bail!("position {position} is outside the receipt"); + } + if !layers.is_empty() { + if turn.state.as_ref().is_some_and(|s| s.bytes.is_none()) { + return Err(self.cannot_open( + &challenge.receipt_id, + CannotOpenReason::StateDropped, + "the recurrent state the turn started from is no longer held", + )); + } + if turn.replays >= MAX_REPLAYS_PER_RECEIPT { + bail!( + "receipt {} was already replayed for {MAX_REPLAYS_PER_RECEIPT} challenges", + challenge.receipt_id + ); + } + turn.replays += 1; + } + let turn: &CommittedTurn = turn; + let lineage = self.lineage(turn, &state.cells, positions)?; + let committed = |position: u32, slot: u64| -> Result { + if let Some(lineage) = lineage.get(&position) { + // a position of the prefix: its leaves are in no tree of + // the turn, and open against the position's digest + let leaf = usize::try_from(slot) + .ok() + .and_then(|slot| lineage.leaves.get(slot)) + .context("leaf outside the committed position")?; + return Ok(Committed { + hash: *leaf, + path: Vec::new(), + }); + } + let index = leaf_index(position, slot, turn.position_start, slots); + Ok(Committed { + hash: turn + .tree + .leaf(index) + .context("leaf outside the committed tree")?, + path: encode_path(&turn.tree.path(index)?), + }) + }; + let mut leaves = BTreeMap::new(); + let written = last_writes(&turn.events, turn.seq); + let mut tokens = BTreeMap::new(); + let mut capture: BTreeMap> = BTreeMap::new(); + let mut boundaries = Boundaries::default(); + for &position in positions { + if lineage.contains_key(&position) { + if start == 0 { + tokens.insert(position, turn.prefix.tokens[position as usize]); + } + } else { + let step = computing_step(&written, position)?; + capture.entry(step).or_default().push(position); + if start == 0 { + tokens.insert(position, recorded_token(turn, &written, position)?); + } + } + for &layer in &layers { + for slot in [ + residual_slot(layer, start), + mixing_slot(layer, start), + residual_slot(layer + 1, start), + ] { + leaves.insert((position, slot), committed(position, slot)?); + } + } + if start > 0 { + boundaries + .entry + .push(boundary_leaf(position, committed(position, 0)?)); + } + let exit = committed(position, residual_slot(self.layers.end, start))?; + boundaries.exit.push(boundary_leaf(position, exit)); + } + for &position in head { + let step = computing_step(&written, position)?; + let captured = capture.entry(step).or_default(); + if !captured.contains(&position) { + captured.push(position); + } + let slot = residual_slot(self.layers.end, start); + leaves.insert((position, slot), committed(position, slot)?); + } + let region = region_plan( + turn, + &written, + &challenge.attention, + &self.layers, + &state.state_layers, + )?; + if let Some(region) = ®ion { + let slot = mixing_slot(region.layer, start); + for position in region.positions() { + leaves.insert((position, slot), committed(position, slot)?); + } + } + let last = capture + .keys() + .chain(region.iter().flat_map(|r| r.mixing.keys())) + .max() + .copied(); + let mut planned = Vec::new(); + if let Some(last) = last.filter(|_| !layers.is_empty()) { + // with the turn's own cells copied, only some ubatches run; a + // recurrent layer's state is known only at the turn's start + let segments = if turn.state.is_some() || region.is_some() { + None + } else { + super::turn_seed::segments(turn, &capture, last, &state.cells)? + }; + let segments = segments.unwrap_or_else(|| { + vec![Segment { + cells: Vec::new(), + events: (0..=last).collect(), + }] + }); + planned = replays(turn, &capture, region.as_ref(), segments); + } + if !layers.is_empty() { + planned.extend(lineage_replays(turn, &lineage)); + } + share_context(&mut planned); + let plan = ReplayPlan { + seq: turn.seq, + replays: planned, + layers: layers.into_iter().collect(), + tokens, + leaves, + region, + prefix: PrefixPlan::of(turn, &lineage), + prefix_tokens: if start == 0 { + turn.prefix.tokens.clone() + } else { + Vec::new() + }, + }; + Ok((plan, boundaries)) + } + + /// Fails unless every cell of `seed` still holds what it held when the + /// turn started. Call it with the stage idle and its reports applied, so + /// no ubatch rewrites a cell before the seed is copied. + pub fn check_seed(&self, seed: &ReplaySeed) -> Result<()> { + self.check_cells(&seed.cells) + } + + /// Fails unless every cell still holds what the turn read or wrote. The + /// error is a [`CannotOpen`]: the stage's own cache no longer holds the + /// turn, whatever the challenge asks. An exposed cell fails here: an + /// opening checks its rows first ([`Self::verify_exposed`]). + pub fn check_cells(&self, cells: &[PrefixCell]) -> Result<()> { + self.check_records(cells, |record| record == CellRecord::Held) + } + + /// [`Self::check_cells`] for cells whose rows are read to be checked + /// against their digests: an exposed cell passes. + pub fn check_unseen_overwrite(&self, cells: &[PrefixCell]) -> Result<()> { + self.check_records(cells, |record| { + matches!(record, CellRecord::Held | CellRecord::Exposed) + }) + } + + fn check_records( + &self, + cells: &[PrefixCell], + readable: impl Fn(CellRecord) -> bool, + ) -> Result<()> { + let state = self.lock(); + let lost = cells.iter().find_map(|cell| { + let record = state.cells.record(cell); + (!readable(record)).then_some((cell, record)) + }); + match lost { + Some((cell, record)) => Err(self.lost_cell(cell, record)), + None => Ok(()), + } + } + + /// The error of an opening that reads `cell`, which no longer holds + /// what the turn read or wrote. + pub(super) fn lost_cell(&self, cell: &PrefixCell, record: CellRecord) -> anyhow::Error { + let (reason, what) = match record { + CellRecord::Overwritten => ( + CannotOpenReason::CellsOverwritten, + "was reused by a later request", + ), + CellRecord::Dropped => ( + CannotOpenReason::CellsUnknown, + "was computed by a ubatch the stage no longer holds", + ), + CellRecord::Exposed => ( + CannotOpenReason::CellsUnknown, + "was free when the stage computed a ubatch it could not record, and its \ + rows were not checked since", + ), + _ => ( + CannotOpenReason::CellsUnknown, + "may have been reused: the stage could not follow a change of its KV cache", + ), + }; + self.cannot_open( + "", + reason, + format!( + "the KV cell that held position {} of the turn or its prefix {what}", + cell.pos + ), + ) + } + + /// The token at every position of a committed turn, from its first + /// position. Meaningful on the stage that holds layer 0. + pub fn turn_tokens(&self, receipt_id: &str) -> Result> { + let state = self.lock(); + let turn = turn(&state.committed, receipt_id) + .with_context(|| format!("receipt {receipt_id} is not committed"))?; + let written = last_writes(&turn.events, turn.seq); + (turn.position_start..turn.position_end) + .map(|position| recorded_token(turn, &written, position)) + .collect() + } +} + +/// Names the receipt in a [`CannotOpen`] made where it was not known. +pub(super) fn name_receipt(error: anyhow::Error, receipt_id: &str) -> anyhow::Error { + match error.downcast::() { + Ok(mut cannot) => { + if cannot.receipt_id.is_empty() { + receipt_id.clone_into(&mut cannot.receipt_id); + } + anyhow::Error::new(cannot) + } + Err(error) => error, + } +} + +impl ReplayPlan { + pub(super) fn committed(&self, position: u32, slot: u64) -> Result<&Committed> { + self.leaves + .get(&(position, slot)) + .with_context(|| format!("no committed leaf for position {position}, slot {slot}")) + } +} + +#[derive(Default)] +struct Boundaries { + entry: Vec, + exit: Vec, +} + +fn boundary_leaf(position: u32, committed: Committed) -> BoundaryLeaf { + BoundaryLeaf { + position, + leaf: hex::encode(committed.hash), + path: committed.path, + } +} + +/// The replays of `segments` of `turn`, each from the prefix and the +/// segment's own cells, in replay contexts of one size. +fn replays( + turn: &CommittedTurn, + capture: &BTreeMap>, + region: Option<&RegionPlan>, + segments: Vec, +) -> Vec { + let captured = |index: usize| capture.get(&index).cloned().unwrap_or_default(); + // a captured position reports its mixing values with the rest + let mixing = |index: usize, captured: &[u32]| -> Vec { + region + .and_then(|r| r.mixing.get(&index)) + .map(|positions| { + positions + .iter() + .copied() + .filter(|p| !captured.contains(p)) + .collect() + }) + .unwrap_or_default() + }; + let state = turn.state.as_ref().and_then(|state| state.bytes.clone()); + segments + .into_iter() + .map(|segment| { + let steps: Vec = segment + .events + .iter() + .map(|&index| match &turn.events[index] { + Event::Ubatch(record) => { + let capture = captured(index); + ReplayStep::Decode { + record: replay_columns(record, turn.seq), + mixing: mixing(index, &capture), + capture, + } + } + Event::SeqRm { p0, p1 } => ReplayStep::SeqRm { p0: *p0, p1: *p1 }, + }) + .collect(); + let cells: Vec = turn + .prefix + .cells + .iter() + .copied() + .chain(segment.cells) + .collect(); + let seed = (!cells.is_empty() || state.is_some()) + .then(|| seed_for(cells, &steps, state.clone())); + Replay { seed, steps } + }) + .collect() +} + +/// Gives every seeded replay a context of one size, so the replay context +/// is not made again for each. +fn share_context(replays: &mut [Replay]) { + let n_cells = replays + .iter() + .filter_map(|r| r.seed.as_ref()) + .map(|s| s.n_cells) + .max(); + for seed in replays.iter_mut().filter_map(|r| r.seed.as_mut()) { + seed.n_cells = n_cells.unwrap_or(seed.n_cells); + } +} + +/// A replay that starts from `cells`, in a context with room for them and +/// for every cell the steps use. +pub(super) fn seed_for( + cells: Vec, + steps: &[ReplayStep], + state: Option>, +) -> ReplaySeed { + let seeded = cells.iter().map(|c| c.cell + 1).max().unwrap_or(0); + let used = steps + .iter() + .filter_map(|step| match step { + ReplayStep::Decode { record, .. } => Some(record.n_kv), + ReplayStep::SeqRm { .. } => None, + }) + .max() + .unwrap_or(0); + ReplaySeed { + cells, + n_cells: seeded.max(used), + state, + } +} + +/// The event of the ubatch that computed `position` of the turn's sequence +/// last, by the turn's [`last_writes`]. +pub(super) fn computing_step(written: &BTreeMap, position: u32) -> Result { + written + .get(&position) + .map(|written| written.event) + .with_context(|| format!("no recorded ubatch computed position {position}")) +} + +/// The token the turn fed at `position`: the one of the ubatch that +/// computed the position last. +fn recorded_token( + turn: &CommittedTurn, + written: &BTreeMap, + position: u32, +) -> Result { + written + .get(&position) + .and_then(|written| Some(turn.events[written.event].ubatch()?.token[written.col])) + .with_context(|| format!("no recorded token at position {position}")) +} + +/// A recorded ubatch as `seq` replays it: other sequences' columns become +/// dummy tokens at positions 0.. of their own sequence, with zero inputs. A +/// ubatch of `seq` alone is shared as recorded. +pub(super) fn replay_columns(record: &Arc, seq: i32) -> Arc { + if record.seq.iter().all(|&s| s == seq) { + return Arc::clone(record); + } + let mut out = UbatchRecord::clone(record); + let mut next_pos: BTreeMap = BTreeMap::new(); + for col in 0..record.seq.len() { + if record.seq[col] == seq { + continue; + } + out.token[col] = DUMMY_TOKEN; + let pos = next_pos.entry(record.seq[col]).or_insert(0); + out.pos[col] = *pos; + *pos += 1; + if let Some(input) = &mut out.input { + let row = input.row_bytes; + input.rows[col * row..(col + 1) * row].fill(0); + } + } + Arc::new(out) +} diff --git a/crates/skippy-receipts/src/recorder/stream_tests.rs b/crates/skippy-receipts/src/recorder/stream_tests.rs new file mode 100644 index 00000000..894a77dc --- /dev/null +++ b/crates/skippy-receipts/src/recorder/stream_tests.rs @@ -0,0 +1,45 @@ +//! A stage whose KV cache keeps a stream per sequence, on the test model of +//! `tests.rs`. + +use super::*; + +/// Sequence 3 computes a prompt, sequence 2 writes the same cells of its +/// own stream, and sequence 1 continues the prompt from a copy of +/// sequence 3's stream. +fn continued(streams: KvStreams) -> Recorder { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.set_kv_streams(streams); + record( + &recorder, + ubatch(&[(3, 0), (3, 1), (3, 2)], &[0, 1, 2], true), + ); + record(&recorder, ubatch(&[(2, 0)], &[0], true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 3), (1, 4)], &[3, 4], true)); + recorder +} + +#[test] +fn each_sequence_keeps_its_cells_in_its_own_stream() { + let recorder = continued(KvStreams::PerSequence); + recorder.commit("r1", 1, TurnId::default(), 3..5).unwrap(); + let pinned = recorder.pinned_cells(std::time::Instant::now()); + let expected: Vec = (0..5).map(|cell| KvCell { stream: 1, cell }).collect(); + assert_eq!(pinned, expected, "the prefix was copied into stream 1"); + // another lane writing its own stream leaves the turn's cells alone + record(&recorder, ubatch(&[(2, 1), (2, 2)], &[1, 2], true)); + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge(&[(2, &[4])]), &replayer).unwrap(); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + assert!(seed.cells.iter().all(|c| c.stream == 1)); + assert_eq!(&seed.indices()[..3], &[0, 1, 2]); + recorder.check_seed(&seed).unwrap(); +} + +#[test] +fn a_shared_stream_loses_the_cells_another_lane_writes() { + let recorder = continued(KvStreams::Shared); + // sequence 2 wrote cell 0 before the copy, so the prompt's first + // position is gone from the cache + assert!(recorder.commit("r1", 1, TurnId::default(), 3..5).is_err()); +} diff --git a/crates/skippy-receipts/src/recorder/tests.rs b/crates/skippy-receipts/src/recorder/tests.rs new file mode 100644 index 00000000..a42f179a --- /dev/null +++ b/crates/skippy-receipts/src/recorder/tests.rs @@ -0,0 +1,967 @@ +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; + +use anyhow::Result; + +use super::*; +use crate::binding::{verify_paths, verify_shape}; +use crate::layer_tensors::{ + FLAG_ROUTER, GGML_F32, GGML_I32, TensorColumn, TensorKind, UbatchColumns, f32_bytes, i32_bytes, +}; +use crate::wire::{ + CannotOpen, CannotOpenReason, Challenge, MixingKind, Opening, Pick, RECEIPT_VERSION, Receipt, + StageCommitment, TensorOpening, encode_f32, +}; + +/// The model has four layers; stage 0 holds 0..2 and stage 1 holds 2..4. +const MODEL_LAYERS: u32 = 4; +const STAGES: [Range; 2] = [0..2, 2..4]; +/// ggml type of the stored rows: f16. +const CACHE_TYPE: i32 = 1; + +/// A deterministic stand-in for the values a layer computes for a token. +fn value(layer: u32, kind: TensorKind, index: u32, token: i32, position: i32) -> Vec { + let base = layer as f32 * 100.0 + + kind.code() as f32 + + index as f32 * 10.0 + + token as f32 * 0.25 + + position as f32 * 0.5; + vec![base, base + 1.0, -base] +} + +type Key = (u32, TensorKind, u32, usize); + +/// A stage of the test model. `entry_offset` shifts the residual it +/// receives, as a stage that does not use the previous stage's output would. +/// The token mixing of `state_layers` reads a recurrent state, which each +/// ubatch reports at the first position of every sequence. +#[derive(Clone)] +struct Stage { + layers: Range, + entry_offset: f32, + state_layers: Vec, +} + +impl Stage { + fn new(index: usize) -> Self { + Self { + layers: STAGES[index].clone(), + entry_offset: 0.0, + state_layers: Vec::new(), + } + } +} + +/// Columns of a ubatch computed by `value`: per layer a mixing input, a +/// stored row and a mixing output; in opened layers also four attention +/// matmuls and two FFN matmuls (one with experts) with a selection. The +/// model's final layer keeps the FFN and its residual out only for output +/// rows. +struct Columns(HashMap)>); + +impl Columns { + fn new(record: &UbatchRecord, stage: &Stage, open: &[u32]) -> Self { + let mut columns = Self(HashMap::new()); + for col in 0..record.token.len() { + let (token, pos) = (record.token[col], record.pos[col]); + let f32_at = |layer, kind, index| f32_bytes(&value(layer, kind, index, token, pos)); + let output = record.output[col] != 0; + for layer in stage.layers.clone() { + for kind in [ + TensorKind::Residual, + TensorKind::MixingInput, + TensorKind::MixingOutput, + ] { + let mut values = value(layer, kind, 0, token, pos); + if kind == TensorKind::Residual && layer == stage.layers.start { + values.iter_mut().for_each(|v| *v += stage.entry_offset); + } + columns.put((layer, kind, 0, col), GGML_F32, 0, "", f32_bytes(&values)); + } + let stored = stored_row(layer, token, pos); + columns.put( + (layer, TensorKind::MixingStored, 0, col), + CACHE_TYPE, + 0, + "", + stored, + ); + if open.contains(&layer) { + let full = output || layer + 1 < MODEL_LAYERS; + columns.add_matmuls(layer, col, if full { 6 } else { 4 }, &f32_at); + } + } + let end = stage.layers.end; + if end < MODEL_LAYERS || output { + let key = (end, TensorKind::Residual, 0, col); + columns.put(key, GGML_F32, 0, "", f32_at(end, TensorKind::Residual, 0)); + } + } + columns.add_states(record, stage); + columns + } + + /// The state each sequence's token mixing read before its first + /// position of the ubatch, the one its previous position left. + fn add_states(&mut self, record: &UbatchRecord, stage: &Stage) { + let mut first: HashMap = HashMap::new(); + for col in 0..record.pos.len() { + let entry = first.entry(record.seq[col]).or_insert(col); + if record.pos[col] < record.pos[*entry] { + *entry = col; + } + } + for &col in first.values() { + for &layer in &stage.state_layers { + let state = value(layer, TensorKind::MixingState, 0, 0, record.pos[col]); + let key = (layer, TensorKind::MixingState, 0, col); + self.put(key, GGML_F32, 0, "", f32_bytes(&state)); + } + } + } + + fn put(&mut self, key: Key, ggml_type: i32, flags: i32, name: &str, bytes: Vec) { + self.0 + .insert(key, (ggml_type, flags, name.to_owned(), bytes)); + } + + fn add_matmuls( + &mut self, + layer: u32, + col: usize, + count: u32, + f32_at: &dyn Fn(u32, TensorKind, u32) -> Vec, + ) { + for index in 0..count { + let name = format!("blk.{layer}.w{index}.weight"); + let flags = if index == 4 { FLAG_ROUTER } else { 0 }; + for kind in [TensorKind::MatmulInput, TensorKind::MatmulOutput] { + self.put( + (layer, kind, index, col), + GGML_F32, + flags, + &name, + f32_at(layer, kind, index), + ); + } + } + if count > 4 { + let ids = i32_bytes(&[3, 1]); + self.put( + (layer, TensorKind::ExpertIds, 5, col), + GGML_I32, + 0, + "", + ids.clone(), + ); + self.put((layer, TensorKind::Selection, 0, col), GGML_I32, 0, "", ids); + } + } +} + +impl UbatchColumns for Columns { + fn count(&self, layer: u32, kind: TensorKind) -> u32 { + self.0 + .keys() + .filter(|k| k.0 == layer && k.1 == kind) + .map(|k| k.2 + 1) + .max() + .unwrap_or(0) + } + + fn column( + &self, + layer: u32, + kind: TensorKind, + index: u32, + col: usize, + ) -> Option> { + self.0 + .get(&(layer, kind, index, col)) + .map(|(ggml_type, flags, name, bytes)| TensorColumn { + ggml_type: *ggml_type, + flags: *flags, + name, + bytes, + digest: None, + }) + } +} + +fn ubatch(columns: &[(i32, i32)], cells: &[u32], output_last: bool) -> UbatchRecord { + let n = columns.len(); + let mut output = vec![0; n]; + if output_last { + output[n - 1] = 1; + } + UbatchRecord { + token: columns.iter().map(|(_, p)| 1000 + p).collect(), + seq: columns.iter().map(|(s, _)| *s).collect(), + pos: columns.iter().map(|(_, p)| *p).collect(), + output, + cell: cells.to_vec(), + n_kv: 256, + input: Some(StageInput { + rows: vec![7; n * 4], + row_bytes: 4, + ggml_type: 0, + }), + } +} + +fn record_on(recorder: &Recorder, stage: &Stage, record: UbatchRecord) { + let columns = Columns::new(&record, stage, &[]); + recorder.record_ubatch(record, &columns); +} + +/// Records on a lone recorder for stage 1. +fn record(recorder: &Recorder, record: UbatchRecord) { + record_on(recorder, &Stage::new(1), record); +} + +/// A replay a [`FakeReplayer`] ran: the cells it copied and what each of +/// its steps captured. +type Run = (Vec, Vec>); + +/// Replays by recomputing `value`, and keeps the steps it was given. +struct FakeReplayer { + stage: Stage, + steps: RefCell>, + seed: RefCell>, + /// Every replay: its seed's cells and its steps' captures. + runs: RefCell>, + layers: RefCell>, + replays: Cell, + /// Reads of stored rows. + row_reads: Cell, + /// The scope of every replay. + scopes: RefCell>, + /// The anchors of every anchored replay. + anchors: RefCell>, + corrupt: bool, + /// Reads rows a later write left in the cells, not the turn's. + stale_rows: bool, + /// Corrupts the committed values of full replays, anchored or not, as a + /// backend that fuses kernels differently when more tensors are marked + /// does. + fused: bool, + /// The attention layout every replayed layer reports. + attention: Option, +} + +impl FakeReplayer { + fn new(stage: Stage) -> Self { + Self { + stage, + steps: RefCell::default(), + seed: RefCell::default(), + runs: RefCell::default(), + layers: RefCell::default(), + replays: Cell::new(0), + row_reads: Cell::new(0), + scopes: RefCell::default(), + anchors: RefCell::default(), + corrupt: false, + stale_rows: false, + fused: false, + attention: None, + } + } + + fn for_stage(index: usize) -> Self { + Self::new(Stage::new(index)) + } +} + +impl Replayer for FakeReplayer { + fn replay( + &self, + seq: i32, + layers: &[u32], + scope: ReplayScope<'_>, + seed: Option<&ReplaySeed>, + steps: &[ReplayStep], + ) -> Result> { + *self.steps.borrow_mut() = steps.to_vec(); + *self.seed.borrow_mut() = seed.cloned(); + self.runs.borrow_mut().push(( + seed.map(ReplaySeed::indices).unwrap_or_default(), + steps.iter().map(step_capture).collect(), + )); + *self.layers.borrow_mut() = layers.to_vec(); + self.replays.set(self.replays.get() + 1); + let name = match scope { + ReplayScope::Full => "full", + ReplayScope::Committed => "committed", + ReplayScope::Anchored(anchors) => { + self.anchors.borrow_mut().extend_from_slice(anchors); + "anchored" + } + }; + self.scopes.borrow_mut().push(name); + let corrupt = self.corrupt || (self.fused && scope != ReplayScope::Committed); + let mut out = Vec::new(); + for step in steps { + let ReplayStep::Decode { + record, + capture, + mixing, + } = step + else { + continue; + }; + let columns = Columns::new(record, &self.stage, layers); + for col in 0..record.pos.len() { + let position = u32::try_from(record.pos[col])?; + if record.seq[col] != seq { + continue; + } + if mixing.contains(&position) { + for &layer in layers { + let values = ReplayedLayer::from_mixing_columns(layer, &columns, col); + out.push((position, layer, values)); + } + } + if !capture.contains(&position) { + continue; + } + for &layer in layers { + let mut values = ReplayedLayer::from_columns(layer, &columns, col)?; + values.attention.extend(self.attention.clone().map(Ok)); + if corrupt && let Some((_, bytes)) = &mut values.mixing[0].value { + bytes[0] ^= 1; + } + out.push((position, layer, values)); + } + } + } + Ok(out) + } + + /// The stored row the test model writes at each cell's position, for a + /// token [`ubatch`] puts there. + fn read_rows(&self, layer: u32, cells: &[PrefixCell]) -> Result> { + self.row_reads.set(self.row_reads.get() + 1); + let token = |pos: i32| if self.stale_rows { 0 } else { 1000 + pos }; + let values = cells + .iter() + .flat_map(|c| stored_row(layer, token(c.pos), c.pos)) + .collect(); + Ok(vec![StoredRows { + ggml_type: CACHE_TYPE, + row_bytes: 6, + values, + }]) + } + + fn pin_cells(&self, _cells: &[KvCell]) -> Result<()> { + Ok(()) + } +} + +fn step_capture(step: &ReplayStep) -> Vec { + match step { + ReplayStep::Decode { capture, .. } => capture.clone(), + ReplayStep::SeqRm { .. } => Vec::new(), + } +} + +fn stored_row(layer: u32, token: i32, position: i32) -> Vec { + value(layer, TensorKind::MixingStored, 0, token, position) + .iter() + .flat_map(|v| half::f16::from_f32(*v).to_le_bytes()) + .collect() +} + +/// A two-stage node: both stages record the same ubatches. +struct Node { + stages: [Recorder; 2], + replayers: [FakeReplayer; 2], +} + +impl Node { + fn new() -> Self { + Self::with_stages([Stage::new(0), Stage::new(1)]) + } + + fn with_stages(stages: [Stage; 2]) -> Self { + Self { + stages: [0, 1].map(|i| { + Recorder::new(i as u32, stages[i].layers.clone(), "cpu").holding_output(i == 1) + }), + replayers: stages.map(FakeReplayer::new), + } + } + + fn record(&self, record: UbatchRecord) { + for (recorder, replayer) in self.stages.iter().zip(&self.replayers) { + record_on(recorder, &replayer.stage, record.clone()); + } + } + + /// A prompt of three tokens for sequence 7, then a decode step batched + /// with sequence 9. + fn two_lane_turn() -> Self { + let node = Self::new(); + node.record(ubatch(&[(7, 0), (7, 1), (7, 2)], &[0, 1, 2], true)); + node.record(ubatch(&[(9, 40), (7, 3)], &[8, 3], true)); + node + } + + /// Commits sequence `seq` at `positions` on both stages, generation + /// starting at `generation_start`. + fn commit(&self, seq: i32, positions: Range, generation_start: u32) -> Receipt { + let stages = self + .stages + .iter() + .map(|s| { + s.commit("r1", seq, TurnId::default(), positions.clone()) + .unwrap() + }) + .collect(); + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r1".into(), + model: "m".into(), + position_start: positions.start, + position_end: positions.end, + tokens: self.stages[0].turn_tokens("r1").unwrap(), + generation_start, + final_token: Some(2000), + stages, + binding: None, + } + } + + fn open(&self, challenge: &Challenge) -> Result { + let stages = self + .stages + .iter() + .zip(&self.replayers) + .map(|(recorder, replayer)| recorder.open(challenge, replayer)) + .collect::>()?; + Ok(Opening { + receipt_id: challenge.receipt_id.clone(), + stages, + }) + } +} + +fn challenge(picks: &[(u32, &[u32])]) -> Challenge { + Challenge { + receipt_id: "r1".into(), + picks: picks + .iter() + .map(|(layer, positions)| Pick { + layer: *layer, + positions: positions.to_vec(), + }) + .collect(), + proof: None, + head: Vec::new(), + attention: Vec::new(), + } +} + +/// Position 1 is not an output row: on the model's final layer its +/// residual out, FFN matmuls and selection are absent. Position 3 has them +/// all. +fn check_final_layer(opening: &Opening) { + let layer = &opening.stages[1].layers[0]; + assert_eq!(layer.layer, 3); + let (early, output) = (&layer.leaves[0], &layer.leaves[1]); + assert!(early.residual_out.is_none()); + assert_eq!(early.matrices.len(), 4); + assert!(early.selections.is_empty()); + assert_eq!(output.matrices.len(), 6); + assert_eq!(output.mixing.len(), 3); + assert_eq!(output.mixing[1].kind, crate::wire::MixingKind::Stored); + assert_eq!(output.mixing[1].ggml_type, CACHE_TYPE); + assert!(output.matrices[4].router); + assert_eq!(output.matrices[5].experts, Some(vec![3, 1])); + assert_eq!(output.selections[0].ids, vec![3, 1]); + assert_eq!(output.matrices[2].weight, "blk.3.w2.weight"); +} + +#[test] +fn a_replayed_opening_verifies_against_the_roots() { + let node = Node::two_lane_turn(); + assert_eq!( + node.stages[0].recorded_range(7, TurnId::default()), + Some(0..4) + ); + let receipt = node.commit(7, 0..4, 3); + assert_eq!(receipt.stages[1].leaf_count, 4 * 5); + assert_eq!(receipt.tokens, vec![1000, 1001, 1002, 1003]); + verify_shape(&receipt, MODEL_LAYERS).unwrap(); + let challenge = challenge(&[(1, &[0, 2]), (3, &[1, 3])]); + let opening = node.open(&challenge).unwrap(); + assert_eq!(receipt.stages[1].cache_types, vec!["f16".to_string()]); + verify_paths(&receipt, &challenge, &opening).unwrap(); + check_final_layer(&opening); + // the input of layer 0 and the boundary at every picked position + let positions = [0, 1, 2, 3]; + let anchors: Vec = opening.stages[0] + .anchors + .iter() + .map(|a| a.position) + .collect(); + assert_eq!(anchors, positions); + assert_eq!(opening.stages[0].anchors[3].token, 1003); + assert_eq!(opening.stages[1].entry.len(), positions.len()); + assert!(opening.stages[0].entry.is_empty()); + + // a receipt that does not name the stored rows' type is refused + let mut unnamed = receipt; + unnamed.stages[1].cache_types = vec!["q8_0".into()]; + assert!(verify_paths(&unnamed, &challenge, &opening).is_err()); + + // stage 0 replays layer 1 and layer 0 for the anchors, in one pass + assert_eq!(*node.replayers[0].layers.borrow(), vec![0, 1]); + let steps = node.replayers[1].steps.borrow(); + let ReplayStep::Decode { + record, capture, .. + } = &steps[1] + else { + panic!("decode step"); + }; + // The other lane's column is a dummy at its recorded cell. + assert_eq!(record.seq, vec![9, 7]); + assert_eq!(record.token, vec![DUMMY_TOKEN, 1003]); + assert_eq!(record.pos, vec![0, 3]); + assert_eq!(record.cell, vec![8, 3]); + assert_eq!( + record.input.as_ref().unwrap().rows, + vec![0, 0, 0, 0, 7, 7, 7, 7] + ); + assert_eq!(capture, &vec![3]); +} + +#[test] +fn the_input_of_layer_0_binds_the_token() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + let challenge = challenge(&[(2, &[1, 3])]); + let opening = node.open(&challenge).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + // a receipt over other tokens no longer matches the committed leaves + let mut other = receipt.clone(); + other.tokens[3] = 1500; + assert!(verify_paths(&other, &challenge, &opening).is_err()); + // and an anchor that names those tokens no longer hashes to its leaf + let mut forged = opening.clone(); + forged.stages[0].anchors[1].token = 1500; + assert!(verify_paths(&other, &challenge, &forged).is_err()); + // an anchor must be opened at every picked position + let mut missing = opening; + missing.stages[0].anchors.remove(0); + assert!(verify_paths(&receipt, &challenge, &missing).is_err()); +} + +#[test] +fn a_stage_must_receive_what_the_previous_stage_sent() { + let mut shifted = Stage::new(1); + shifted.entry_offset = 0.5; + let node = Node::with_stages([Stage::new(0), shifted]); + node.record(ubatch(&[(7, 0), (7, 1)], &[0, 1], true)); + let receipt = node.commit(7, 0..2, 1); + let challenge = challenge(&[(2, &[0, 1])]); + let opening = node.open(&challenge).unwrap(); + let error = verify_paths(&receipt, &challenge, &opening).unwrap_err(); + assert!( + error.to_string().contains("different residual"), + "{error:#}" + ); +} + +#[test] +fn a_stage_without_picks_opens_its_boundaries_without_a_replay() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + let challenge = challenge(&[(1, &[2, 3])]); + let opening = node.open(&challenge).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + assert_eq!(node.replayers[1].replays.get(), 0); + assert!(opening.stages[1].layers.is_empty()); + assert_eq!(opening.stages[1].entry.len(), 2); +} + +#[test] +fn a_replay_that_diverges_is_refused() { + let node = Node::two_lane_turn(); + node.commit(7, 0..4, 3); + let mut replayer = FakeReplayer::for_stage(1); + replayer.corrupt = true; + let error = node.stages[1] + .open(&challenge(&[(2, &[2])]), &replayer) + .unwrap_err(); + assert!( + format!("{error:#}").contains("replay diverged"), + "{error:#}" + ); +} + +#[test] +fn a_full_replay_that_diverges_is_anchored_to_the_committed_values() { + let node = Node::two_lane_turn(); + node.commit(7, 0..4, 3); + let mut replayer = FakeReplayer::for_stage(1); + replayer.fused = true; + let challenge = challenge(&[(2, &[2])]); + let opened = node.stages[1].open(&challenge, &replayer).unwrap(); + assert_eq!(*replayer.scopes.borrow(), ["full", "committed", "anchored"]); + let anchors = replayer.anchors.borrow(); + assert!(!anchors.is_empty()); + assert!(anchors.iter().all(|a| a.pos == 2 && a.seq == 7)); + // a fresh node: openings are cached + let fresh = Node::two_lane_turn(); + fresh.commit(7, 0..4, 3); + let honest = FakeReplayer::for_stage(1); + let expected = fresh.stages[1].open(&challenge, &honest).unwrap(); + assert_eq!(opened, expected); + assert_eq!(*honest.scopes.borrow(), ["full"]); +} + +#[test] +fn the_final_stage_opens_the_output_residual() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + assert_eq!(receipt.output_positions(), 2..4); + let mut challenge = challenge(&[(1, &[0])]); + challenge.head = vec![2, 3]; + let opening = node.open(&challenge).unwrap(); + verify_paths(&receipt, &challenge, &opening).unwrap(); + assert!(opening.stages[0].head.is_empty()); + let head = &opening.stages[1].head; + assert_eq!(head.iter().map(|h| h.position).collect::>(), [2, 3]); + // the final stage replays its last layer for the head alone + assert_eq!(*node.replayers[1].layers.borrow(), vec![3]); + assert_eq!( + head[1].residual_values().unwrap(), + value(4, TensorKind::Residual, 0, 1003, 3) + ); + + let mut forged = opening.clone(); + forged.stages[1].head[0].residual = encode_f32(&[1.0, 2.0, 3.0]); + assert!(verify_paths(&receipt, &challenge, &forged).is_err()); + let mut missing = opening; + missing.stages[1].head.pop(); + assert!(verify_paths(&receipt, &challenge, &missing).is_err()); + + // position 1 is not an output row: no token was sampled from it + let mut early = challenge.clone(); + early.head = vec![1]; + let error = node.stages[1].open(&early, &node.replayers[1]).unwrap_err(); + assert!( + format!("{error:#}").contains("not an output row"), + "{error:#}" + ); +} + +#[test] +fn a_forged_opening_fails_its_path() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + let challenge = challenge(&[(2, &[0])]); + let mut opening = node.open(&challenge).unwrap(); + opening.stages[1].layers[0].leaves[0].residual_in = encode_f32(&[1.0, 2.0, 3.0]); + assert!(verify_paths(&receipt, &challenge, &opening).is_err()); +} + +#[test] +fn removed_positions_are_replayed_as_removals() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + // A rejected draft: position 3 is computed, removed, and computed again. + record(&recorder, ubatch(&[(1, 2), (1, 3)], &[2, 3], true)); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, 3, -1); + record(&recorder, ubatch(&[(1, 3)], &[5], true)); + recorder.commit("r1", 1, TurnId::default(), 0..4).unwrap(); + // serving drops the turn's cells from position 2, and another request + // writes cell 2, so the replay starts at the ubatch that wrote position + // 2, before the removal + recorder.memory_op(MemoryOp::SeqRm, 1, -1, 2, -1); + record(&recorder, ubatch(&[(2, 0)], &[2], true)); + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge(&[(2, &[3])]), &replayer).unwrap(); + let steps = replayer.steps.borrow(); + assert_eq!(steps.len(), 3); + assert_eq!(steps[1], ReplayStep::SeqRm { p0: 3, p1: -1 }); + let ReplayStep::Decode { + record, capture, .. + } = &steps[2] + else { + panic!("decode step"); + }; + assert_eq!((record.cell.clone(), capture.clone()), (vec![5], vec![3])); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + assert_eq!(seed.positions(), vec![0, 1]); +} + +#[test] +fn a_cleared_turn_can_still_be_committed() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + assert_eq!(recorder.recorded_range(1, TurnId::default()), Some(0..2)); + recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + assert_eq!(recorder.recorded_range(1, TurnId::default()), None); +} + +#[test] +fn a_shared_prefix_seeds_the_replay() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // a cached prompt in sequence 3, shared with sequence 1, which continues it + record( + &recorder, + ubatch(&[(3, 0), (3, 1), (3, 2)], &[0, 1, 2], true), + ); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, -1, -1); + record(&recorder, ubatch(&[(1, 3), (1, 4)], &[3, 4], true)); + let commitment = recorder.commit("r1", 1, TurnId::default(), 3..5).unwrap(); + let prefix = commitment.prefix.expect("a prefix commitment"); + assert_eq!(prefix.positions, 3); + + let replayer = FakeReplayer::for_stage(1); + recorder.open(&challenge(&[(2, &[4])]), &replayer).unwrap(); + // only the turn's own ubatch is replayed, on top of the shared cells + assert_eq!(replayer.steps.borrow().len(), 1); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + assert_eq!(seed.indices(), vec![0, 1, 2]); + assert_eq!(seed.positions(), vec![0, 1, 2]); + assert_eq!(seed.n_cells, 256); + // a later stage commits the prefix's cells and leaves, not its tokens + assert_eq!(prefix.root.len(), 64); + assert_eq!(prefix.tokens, None); + recorder.check_seed(&seed).unwrap(); + + // once another sequence reuses a cell, the prefix is gone + recorder.memory_op(MemoryOp::SeqRm, 3, -1, -1, -1); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + record(&recorder, ubatch(&[(5, 0)], &[1], true)); + let error = recorder.check_seed(&seed).unwrap_err(); + assert!(format!("{error:#}").contains("reused"), "{error:#}"); +} + +#[test] +fn a_continued_sequence_replays_only_its_new_turn() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record( + &recorder, + ubatch(&[(1, 0), (1, 1), (1, 2)], &[0, 1, 2], true), + ); + assert!( + recorder + .commit("r1", 1, TurnId::default(), 0..3) + .unwrap() + .prefix + .is_none() + ); + record(&recorder, ubatch(&[(1, 3)], &[3], true)); + record(&recorder, ubatch(&[(1, 4)], &[4], true)); + assert_eq!(recorder.recorded_range(1, TurnId::default()), Some(3..5)); + let commitment = recorder.commit("r2", 1, TurnId::default(), 3..5).unwrap(); + assert_eq!(commitment.ubatches, vec![3, 4]); + assert_eq!(commitment.prefix.unwrap().positions, 3); + let replayer = FakeReplayer::for_stage(1); + let mut challenge = challenge(&[(3, &[3])]); + challenge.receipt_id = "r2".into(); + recorder.open(&challenge, &replayer).unwrap(); + assert_eq!(replayer.steps.borrow().len(), 1); + assert_eq!( + replayer.seed.borrow().as_ref().unwrap().indices(), + vec![0, 1, 2] + ); +} + +#[test] +fn cells_taken_mid_turn_make_the_turn_unreceiptable() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(3, 0), (3, 1)], &[0, 1], true)); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[4, 5], true)); + recorder.memory_op(MemoryOp::SeqCp, 3, 1, 0, 2); + let error = recorder + .commit("r1", 1, TurnId::default(), 0..2) + .unwrap_err(); + assert!(format!("{error:#}").contains("mid-turn"), "{error:#}"); + // the next turn starts afresh + recorder.memory_op(MemoryOp::SeqRm, 1, -1, -1, -1); + record(&recorder, ubatch(&[(1, 0)], &[4], true)); + recorder.commit("r2", 1, TurnId::default(), 0..1).unwrap(); +} + +#[test] +fn a_turn_after_a_shift_has_no_known_prefix() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r1", 1, TurnId::default(), 0..2).unwrap(); + recorder.memory_op(MemoryOp::SeqShift, 1, -1, 0, -1); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + let error = recorder + .commit("r2", 1, TurnId::default(), 2..3) + .unwrap_err(); + assert!( + format!("{error:#}").contains("prefix is unknown"), + "{error:#}" + ); +} + +#[test] +fn a_turn_on_a_quantized_kv_cache_is_unreceiptable() { + // An honest stage with a q8_0 cache fails the loose attention check, + // so its turns get no receipt, whatever else is in order. + for quantized in [crate::ggml_types::GGML_Q8_0, crate::ggml_types::GGML_Q4_0] { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let turn = ubatch(&[(1, 0), (1, 1)], &[0, 1], true); + let mut columns = Columns::new(&turn, &Stage::new(1), &[]); + for (key, column) in &mut columns.0 { + if key.1 == TensorKind::MixingStored { + column.0 = quantized as i32; + } + } + recorder.record_ubatch(turn, &columns); + let error = recorder + .commit("r", 1, TurnId::default(), 0..2) + .unwrap_err(); + let message = format!("{error:#}"); + assert!(message.contains("quantized KV cache"), "{message}"); + assert!( + message.contains(&crate::ggml_types::type_name(quantized)), + "{message}" + ); + } + // the same turn on an f16 cache commits + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + recorder.commit("r", 1, TurnId::default(), 0..2).unwrap(); +} + +#[test] +fn a_gap_in_the_turn_is_refused() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0)], &[0], true)); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + assert!(recorder.commit("r", 1, TurnId::default(), 0..3).is_err()); +} + +#[test] +fn a_repeated_challenge_is_answered_without_a_replay() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + let challenge = challenge(&[(3, &[1, 3])]); + let first = node.open(&challenge).unwrap(); + let again = node.open(&challenge).unwrap(); + assert_eq!(node.replayers[1].replays.get(), 1); + assert_eq!(first, again); + verify_paths(&receipt, &challenge, &again).unwrap(); +} + +#[test] +fn a_new_turn_under_the_same_id_drops_its_old_openings() { + let node = Node::two_lane_turn(); + node.commit(7, 0..4, 3); + let challenge = challenge(&[(2, &[3])]); + let first = node.open(&challenge).unwrap(); + node.record(ubatch(&[(7, 4)], &[4], true)); + node.commit(7, 4..5, 4); + // position 3 is a position of the new turn's prefix: the stage opens + // it anew, and not with what it opened for the old turn + let again = node.open(&challenge).unwrap(); + assert_ne!(first, again); + assert_eq!(again.stages[1].prefix.len(), 1); + assert_eq!(node.replayers[1].replays.get(), 2); + // a position past the new turn is outside it + let mut past = challenge.clone(); + past.picks[0].positions = vec![5]; + let error = node.open(&past).unwrap_err(); + assert!( + format!("{error:#}").contains("outside the receipt"), + "{error:#}" + ); +} + +#[test] +fn a_receipt_is_replayed_for_a_bounded_number_of_challenges() { + let node = Node::two_lane_turn(); + node.commit(7, 0..4, 3); + let recorder = &node.stages[1]; + let replayer = FakeReplayer::for_stage(1); + let positions: [&[u32]; 5] = [&[0], &[1], &[2], &[3], &[0, 1]]; + for (i, positions) in positions.into_iter().enumerate() { + let opened = recorder.open(&challenge(&[(2, positions)]), &replayer); + if i < MAX_REPLAYS_PER_RECEIPT as usize { + opened.unwrap(); + } else { + let error = opened.unwrap_err(); + assert!( + format!("{error:#}").contains("already replayed"), + "{error:#}" + ); + } + } + // an opening already made is still answered + recorder.open(&challenge(&[(2, &[0])]), &replayer).unwrap(); + assert_eq!(replayer.replays.get(), MAX_REPLAYS_PER_RECEIPT); +} + +#[test] +fn a_receipt_must_have_the_shape_it_names() { + let node = Node::two_lane_turn(); + let receipt = node.commit(7, 0..4, 3); + verify_shape(&receipt, MODEL_LAYERS).unwrap(); + + let mut other = receipt.clone(); + other.version += 1; + assert!(verify_shape(&other, MODEL_LAYERS).is_err()); + + let mut grown = receipt.clone(); + grown.stages[1].leaf_count += 1; + assert!(verify_shape(&grown, MODEL_LAYERS).is_err()); + + // the stages must cover every layer of the model, from 0 + assert!(verify_shape(&receipt, MODEL_LAYERS + 1).is_err()); + let mut truncated = receipt.clone(); + truncated.stages.pop(); + assert!(verify_shape(&truncated, MODEL_LAYERS).is_err()); + let mut reordered = receipt.clone(); + reordered.stages.swap(0, 1); + assert!(verify_shape(&reordered, MODEL_LAYERS).is_err()); + + let mut short = receipt.clone(); + short.tokens.pop(); + assert!(verify_shape(&short, MODEL_LAYERS).is_err()); + + // only the model's final layer may keep no row for a position + let challenge = challenge(&[(2, &[0, 1])]); + let mut dropped = node.open(&challenge).unwrap(); + dropped.stages[1].layers[0].leaves[1].residual_out = None; + let error = verify_paths(&receipt, &challenge, &dropped).unwrap_err(); + assert!( + error.to_string().contains("opened no residual out"), + "{error:#}" + ); +} + +#[path = "attention_tests.rs"] +mod attention_tests; + +#[path = "recurrent_tests.rs"] +mod recurrent_tests; + +#[path = "stream_tests.rs"] +mod stream_tests; + +#[path = "turn_seed_tests.rs"] +mod turn_seed_tests; + +#[path = "turn_identity_tests.rs"] +mod turn_identity_tests; + +#[path = "cannot_open_tests.rs"] +mod cannot_open_tests; + +#[path = "prefix_tests.rs"] +mod prefix_tests; + +#[path = "budget_tests.rs"] +mod budget_tests; diff --git a/crates/skippy-receipts/src/recorder/turn_commit.rs b/crates/skippy-receipts/src/recorder/turn_commit.rs new file mode 100644 index 00000000..b7b266e0 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/turn_commit.rs @@ -0,0 +1,292 @@ +//! Commits a recorded turn: takes the turn's log, by the turn's identity, +//! and seals its leaves under a Merkle root. + +use std::ops::Range; +use std::time::Instant; + +use anyhow::{Context, Result, bail}; + +use super::cells::TurnPrefix; +use super::event_log::{Event, ubatch_starts}; +use super::{CommittedTurn, Recorder, SeqLog, SeqState, TurnCell, TurnId, cells, pins, recurrent}; +use crate::commitment::{Hash, MerkleTree, prefix_tokens_digest}; +use crate::wire::{PrefixCommitment, StageCommitment}; + +impl Recorder { + /// Commits the leaves that turn `turn` of `seq` recorded in `positions` + /// as receipt `receipt_id`. Fails, taking nothing, unless a log of that + /// very turn covers the positions: the sequence's live log when it + /// still records the turn, else the log kept when the turn ended. A + /// receipt id committed before names the new turn from here on. + pub fn commit( + &self, + receipt_id: &str, + seq: i32, + turn: TurnId, + positions: Range, + ) -> Result { + if positions.is_empty() { + bail!("receipt {receipt_id}: empty position range"); + } + let taken = self.take_covering_turn(receipt_id, seq, turn, &positions)?; + // hashing the turn does not hold the lock the recording waits on + let (commitment, committed) = self.seal(receipt_id, seq, positions, taken)?; + let now = Instant::now(); + let mut state = self.lock(); + // a reused id names a new turn; the old one and its openings are gone + state.discard(receipt_id); + state.drop_unpinned_states(now); + state.drop_stale_logs(now); + // turns a client can still challenge keep what opens them; a turn + // that does not fit beside them gets no receipt + state + .make_room(self.window_bytes, committed.bytes, now) + .with_context(|| format!("receipt {receipt_id}: stage {}", self.stage_index))?; + state.committed_bytes += committed.bytes; + state.committed.push_back(committed); + Ok(commitment) + } + + /// Forgets the committed turn of `receipt_id`: its chain did not + /// commit, so no receipt names it and nothing will open it. + pub fn discard(&self, receipt_id: &str) { + self.lock().discard(receipt_id); + } + + /// Takes the recorded turn `turn` of `seq` that covers `positions`. + fn take_covering_turn( + &self, + receipt_id: &str, + seq: i32, + turn: TurnId, + positions: &Range, + ) -> Result { + let slots = self.slots(); + let recurrent = self.is_recurrent(); + let mut guard = self.lock(); + let state = &mut *guard; + let last_error = state + .last_error + .as_ref() + .map(|e| format!(" ({e})")) + .unwrap_or_default(); + let entry = state.seqs.get_mut(&seq).with_context(|| { + format!( + "receipt {receipt_id}: stage {} recorded nothing for sequence {seq}{last_error}", + self.stage_index, + ) + })?; + let taken = if entry.live.covers(turn, positions) { + take_turn(&mut entry.live, positions, slots, recurrent) + } else if let Some(index) = entry + .retired + .iter() + .rposition(|retired| retired.log.covers(turn, positions)) + { + // the turn ended before its commit: its log is used up here + let mut retired = entry.retired.remove(index).expect("an index of the queue"); + state.retired_bytes -= retired.bytes; + take_turn(&mut retired.log, positions, slots, recurrent) + } else { + bail!( + "receipt {receipt_id}: stage {}: {}{last_error}", + self.stage_index, + uncovered(entry, seq, turn, positions) + ); + }; + // a client may challenge a position of the prefix as soon as it + // holds the receipt + let taken = taken.and_then(|mut turn| { + state.cells.check_lineage(&turn.prefix)?; + turn.lineage_runs = state.cells.lineage_runs(&turn.prefix); + Ok(turn) + }); + taken.map_err(|error| { + anyhow::anyhow!( + "receipt {receipt_id}: stage {}: {error:#}{last_error}", + self.stage_index + ) + }) + } + + /// The commitment of a taken turn, and the turn as the stage keeps it. + fn seal( + &self, + receipt_id: &str, + seq: i32, + positions: Range, + turn: TakenTurn, + ) -> Result<(StageCommitment, CommittedTurn)> { + let tree = MerkleTree::new(turn.leaves)?; + // the stage that holds layer 0 knows the tokens of the prefix + let tokens = (self.layers.start == 0) + .then(|| hex::encode(prefix_tokens_digest(&turn.prefix.tokens))); + let prefix = cells::prefix_root(&turn.prefix)?.map(|root| PrefixCommitment { + root: hex::encode(root), + positions: u32::try_from(turn.prefix.len()).unwrap_or(u32::MAX), + tokens, + }); + let commitment = StageCommitment { + stage_index: self.stage_index, + layer_start: self.layers.start, + layer_end: self.layers.end, + root: hex::encode(tree.root()), + leaf_count: tree.leaf_count(), + backend: self.backend.clone(), + cache_types: turn.cache_types, + prefix, + ubatches: ubatch_starts(&turn.events, seq), + recurrent_state: turn.state.as_ref().map(|s| hex::encode(s.digest)), + }; + let bytes = tree.bytes() + + turn + .cells + .iter() + .map(|c| (c.rests.len() + 1) * size_of::()) + .sum::() + + turn.prefix.bytes() + + turn.events.iter().map(Event::bytes).sum::() + + turn + .state + .as_ref() + .map_or(0, recurrent::TurnState::bytes_held); + let committed = CommittedTurn { + receipt_id: receipt_id.to_owned(), + seq, + position_start: positions.start, + position_end: positions.end, + prefix: turn.prefix, + lineage_runs: turn.lineage_runs, + events: turn.events, + tree, + cells: turn.cells, + attention: Vec::new(), + rows: Default::default(), + bytes, + replays: 0, + pin: pins::Pin::new(Instant::now()), + state: turn.state, + }; + Ok((commitment, committed)) + } +} + +/// Why no log of `turn` covers `positions` of `seq`. +fn uncovered(entry: &SeqState, seq: i32, turn: TurnId, positions: &Range) -> String { + let log = std::iter::once(&entry.live) + .chain(entry.retired.iter().map(|r| &r.log)) + .find(|log| log.turn == turn); + if let Some(log) = log + && log.shed + { + let reason = log.tainted.as_deref().unwrap_or("its log was shed"); + format!("turn {turn} of sequence {seq} gets no receipt: {reason}") + } else if let Some(log) = log { + let missed = if log.missed { + ", and a ubatch the stage could not record ran during the turn, so a receipt must \ + start where the turn did" + } else { + "" + }; + format!( + "turn {turn} of sequence {seq} did not record every one of positions \ + {positions:?}{missed}" + ) + } else { + format!( + "sequence {seq} holds no log of turn {turn}: it records turn {} now, and the log of \ + a turn that ended uncommitted is kept only for a while", + entry.live.turn + ) + } +} + +/// What a commit takes from a sequence's log. +struct TakenTurn { + leaves: Vec, + cells: Vec, + prefix: TurnPrefix, + lineage_runs: Vec, + events: Vec, + cache_types: Vec, + state: Option, +} + +/// Takes the pending turn out of `log`, which then waits for the next turn. +/// A turn that cannot be committed is dropped as well. +fn take_turn( + log: &mut SeqLog, + positions: &Range, + slots: u64, + recurrent: bool, +) -> Result { + let prefix = log.prefix.take(); + let state = log.state.take(); + let events = log.take_events(); + // the log covers the positions ([`SeqLog::covers`]): what fails from + // here fails for any commit of the turn. No later commit can cover a + // position recorded so far, so the log keeps none of them. + log.pending_start = None; + let recorded = std::mem::take(&mut log.leaves); + log.missed = false; + if let Some(reason) = log.tainted.take() { + bail!("the turn cannot be replayed: {reason}"); + } + if let Some(&quantized) = log + .cache_types + .iter() + .find(|&&stored| crate::cache_types::audited(stored).is_none()) + { + // an honest stage would fail the loose attention check + // ([`crate::cache_types`]) + bail!( + "the stage stores KV rows as {}, and no audit covers a quantized KV cache", + crate::cache_types::name(quantized) + ); + } + let prefix = match prefix { + Some(Ok(prefix)) => prefix, + Some(Err(reason)) => bail!("the turn's cached prefix is unknown: {reason}"), + None => bail!("no turn is pending"), + }; + let state = match (recurrent, state) { + (false, _) => None, + (true, Some(Ok(state))) => Some(state), + (true, Some(Err(reason))) => { + bail!("the recurrent state the turn started from is unknown: {reason}") + } + (true, None) => bail!("the stage reported no recurrent state for the turn's start"), + }; + if recurrent && !prefix.is_empty() { + // a client may challenge a prefix position, which the stage opens by + // replaying the ubatch that wrote it; the recurrent state that + // ubatch started from is gone + bail!("a stage with recurrent state cannot open the cached prefix of a turn"); + } + let mut leaves = Vec::with_capacity(positions.len() * usize::try_from(slots)?); + let mut cells = Vec::with_capacity(positions.len()); + for position in positions.clone() { + let committed = recorded + .get(&position) + .with_context(|| format!("computed nothing at position {position}"))?; + leaves.extend_from_slice(&committed.leaves); + cells.push(TurnCell { + digest: committed.cell, + rests: committed.rests.clone(), + }); + } + let cache_types = log + .cache_types + .iter() + .map(|&t| crate::ggml_types::type_name(t as u32)) + .collect(); + Ok(TakenTurn { + leaves, + cells, + prefix, + lineage_runs: Vec::new(), + events, + cache_types, + state, + }) +} diff --git a/crates/skippy-receipts/src/recorder/turn_identity_tests.rs b/crates/skippy-receipts/src/recorder/turn_identity_tests.rs new file mode 100644 index 00000000..54f6bf5d --- /dev/null +++ b/crates/skippy-receipts/src/recorder/turn_identity_tests.rs @@ -0,0 +1,143 @@ +//! A commit takes the log of the turn it names, and no other's. + +use super::*; + +const SEQ: i32 = 1; + +/// A ubatch of `SEQ` at `positions`, whose tokens `request` tells apart +/// from another request's at the same positions. +fn ubatch_of(request: i32, positions: std::ops::Range) -> UbatchRecord { + let mut record = ubatch( + &positions.clone().map(|p| (SEQ, p)).collect::>(), + &positions.map(|p| p as u32).collect::>(), + true, + ); + record.token.iter_mut().for_each(|t| *t += 10_000 * request); + record +} + +/// The root a stage commits for a turn it alone recorded. +fn root_alone(request: i32, positions: std::ops::Range) -> String { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let end = positions.end as u32; + record(&recorder, ubatch_of(request, positions)); + recorder + .commit("alone", SEQ, TurnId::default(), 0..end) + .unwrap() + .root +} + +// Request A's lane is reset and handed to request B before A commits. A's +// commit names A's turn, so it gets A's leaves, although B's log is the +// sequence's live one and covers the same positions. +#[test] +fn a_commit_gets_its_own_turn_after_the_sequence_was_reused() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + let (a, b) = (TurnId(1), TurnId(2)); + recorder.begin_turn(SEQ, a); + record(&recorder, ubatch_of(1, 0..3)); + recorder.memory_op(MemoryOp::SeqRm, SEQ, -1, -1, -1); + recorder.begin_turn(SEQ, b); + record(&recorder, ubatch_of(2, 0..4)); + + assert_eq!(recorder.recorded_range(SEQ, a), Some(0..3)); + assert_eq!(recorder.recorded_range(SEQ, b), Some(0..4)); + let committed = recorder.commit("a", SEQ, a, 0..3).unwrap(); + assert_eq!(committed.root, root_alone(1, 0..3)); + assert_ne!(committed.root, root_alone(2, 0..3)); + // B's turn is untouched, and commits its own leaves + let committed = recorder.commit("b", SEQ, b, 0..4).unwrap(); + assert_eq!(committed.root, root_alone(2, 0..4)); + // A's log was used up by its commit + assert_eq!(recorder.recorded_range(SEQ, a), None); + assert!(recorder.commit("a2", SEQ, a, 0..3).is_err()); +} + +// The same when the lane was not reset whole in between: the session that +// takes the sequence starts a new log. +#[test] +fn a_session_taking_a_sequence_starts_a_new_log() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.begin_turn(SEQ, TurnId(1)); + record(&recorder, ubatch_of(1, 0..3)); + recorder.begin_turn(SEQ, TurnId(2)); + recorder.memory_op(MemoryOp::SeqRm, SEQ, -1, -1, -1); + record(&recorder, ubatch_of(2, 0..3)); + let committed = recorder.commit("b", SEQ, TurnId(2), 0..3).unwrap(); + assert_eq!(committed.root, root_alone(2, 0..3)); + let committed = recorder.commit("a", SEQ, TurnId(1), 0..3).unwrap(); + assert_eq!(committed.root, root_alone(1, 0..3)); +} + +// A commit that names a turn the sequence holds no log of is refused, and +// takes nothing from the turn the sequence records. +#[test] +fn a_commit_of_another_turn_is_refused() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.begin_turn(SEQ, TurnId(2)); + record(&recorder, ubatch_of(2, 0..4)); + for stale in [TurnId::default(), TurnId(1), TurnId(3)] { + let error = recorder.commit("a", SEQ, stale, 0..3).unwrap_err(); + assert!(format!("{error:#}").contains("no log of turn"), "{error:#}"); + assert_eq!(recorder.recorded_range(SEQ, stale), None); + } + let committed = recorder.commit("b", SEQ, TurnId(2), 0..4).unwrap(); + assert_eq!(committed.root, root_alone(2, 0..4)); +} + +// The log of a turn that ended uncommitted waits for its commit only for a +// while, and counts toward the recorder's window meanwhile. +#[test] +fn an_uncommitted_log_expires_and_is_counted() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.begin_turn(SEQ, TurnId(1)); + record(&recorder, ubatch_of(1, 0..3)); + recorder.begin_turn(SEQ, TurnId(2)); + let held = recorder.lock().retired_bytes; + assert!(held > 0, "a retired log holds its events and leaves"); + let later = Instant::now() + RETIRED_LOG_TTL; + recorder.lock().drop_stale_logs(later); + assert_eq!(recorder.lock().retired_bytes, 0); + assert!(recorder.commit("a", SEQ, TurnId(1), 0..3).is_err()); + + // past the window, uncommitted logs go before committed turns + record(&recorder, ubatch_of(2, 0..3)); + recorder.commit("measured", SEQ, TurnId(2), 0..3).unwrap(); + let committed = recorder.lock().committed_bytes; + let window = committed + held + held / 2; + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu").with_window_bytes(window); + recorder.begin_turn(SEQ, TurnId(1)); + record(&recorder, ubatch_of(1, 0..3)); + recorder.commit("kept", SEQ, TurnId(1), 0..3).unwrap(); + for turn in 2..6 { + recorder.begin_turn(SEQ + turn as i32, TurnId(turn)); + record_on(&recorder, &Stage::new(1), { + let mut record = ubatch_of(1, 0..3); + record.seq.fill(SEQ + turn as i32); + record.cell.iter_mut().for_each(|c| *c += 10 * turn as u32); + record + }); + recorder.begin_turn(SEQ + turn as i32, TurnId(100 + turn)); + } + let state = recorder.lock(); + assert_eq!(state.retired_bytes, held, "one uncommitted log fits"); + assert_eq!(state.committed.len(), 1, "the committed turn stayed"); +} + +// A commit forged on the stage port, naming the live turn with positions +// its log cannot commit, is refused without taking the log: the real +// commit still finds it. Here another request's image ran during the +// turn, so a commit must also start where the turn did. +#[test] +fn a_commit_the_log_cannot_cover_leaves_it_for_the_real_one() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + recorder.begin_turn(SEQ, TurnId(1)); + record(&recorder, ubatch_of(1, 0..2)); + recorder.unrecorded_ubatch("a ubatch of embeddings cannot be receipted"); + record(&recorder, ubatch_of(1, 2..3)); + for forged in [0..4, 2..5, 1..3] { + assert!(recorder.commit("forged", SEQ, TurnId(1), forged).is_err()); + } + assert_eq!(recorder.recorded_range(SEQ, TurnId(1)), Some(0..3)); + recorder.commit("real", SEQ, TurnId(1), 0..3).unwrap(); +} diff --git a/crates/skippy-receipts/src/recorder/turn_seed.rs b/crates/skippy-receipts/src/recorder/turn_seed.rs new file mode 100644 index 00000000..67424611 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/turn_seed.rs @@ -0,0 +1,172 @@ +//! A replay that starts from the turn's own cells, not only its prefix. +//! +//! After a turn, the stage's KV cache still holds most of the cells the turn +//! wrote; serving may drop the last ones, past the prefix cache's stride. A +//! replay can copy the cells still held along with the prefix and compute +//! only the ubatches that hold a captured position before the first dropped +//! cell, and every ubatch from that one on. An opening then costs a few +//! ubatches, not a prefill of the whole turn, so a long turn opens within +//! the challenge window. +//! +//! The node runs its own replay, so this is no weaker for the client: the +//! client checks the opened values against leaves committed before the +//! challenge, however the node recomputed them. The copied cells are checked +//! against the turn's committed leaves, so an honest replay reproduces them. +//! +//! The copy equals what the skipped ubatches would write only when the turn +//! wrote its positions in increasing order, removed only ranges of them (a +//! rejected draft removes the tail of its verify window), and nothing the +//! replay computes overwrites a copied cell first. Any other turn replays +//! every ubatch, as before. + +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Context, Result}; + +use super::CommittedTurn; +use super::cells::{CellMirror, PrefixCell}; +use super::event_log::{Event, removed}; +use crate::commitment::Hash; + +/// One replay of consecutive events of the turn, from the turn's cells +/// that the events before them wrote. +/// +/// A replay cannot copy the cells of positions after the ones it computes: +/// llama.cpp requires a sequence's new positions to follow the last one in +/// its cache. So events that are not consecutive replay separately, each +/// from the cells before it. +pub(super) struct Segment { + /// The turn's cells to copy, besides the prefix. + pub cells: Vec, + /// The events to replay, consecutive and in order. + pub events: Vec, +} + +/// The replays that compute the `computed` events from the turn's own cells, +/// the last of which is `last`. `None` when the turn must be replayed in +/// full from its prefix. +pub(super) fn segments( + turn: &CommittedTurn, + computed: &BTreeMap>, + last: usize, + mirror: &CellMirror, +) -> Result>> { + let Some(written) = held_cells(turn) else { + return Ok(None); + }; + let mut cells = Vec::with_capacity(written.len()); + let mut first_lost = last + 1; + for (&pos, &(cell, event)) in &written { + let cell = PrefixCell { + pos, + stream: mirror.streams().of(turn.seq), + cell, + digest: committed_digest(turn, pos)?, + }; + if mirror.holds(&cell) { + cells.push((cell, event)); + } else { + first_lost = first_lost.min(event); + } + } + if first_lost == 0 { + return Ok(None); + } + let events: Vec = computed + .keys() + .copied() + .filter(|&event| event < first_lost) + .chain(first_lost..=last) + .collect(); + let mut segments: Vec = Vec::new(); + for event in events { + match segments.last_mut() { + Some(segment) if segment.events.last() == Some(&(event - 1)) => { + segment.events.push(event); + } + _ => segments.push(Segment { + // the cells written before the segment, all still held + cells: cells + .iter() + .filter(|&&(_, written)| written < event) + .map(|&(cell, _)| cell) + .collect(), + events: vec![event], + }), + } + } + if segments.iter().any(|s| overwrites_a_seeded_cell(turn, s)) { + return Ok(None); + } + Ok(Some(segments)) +} + +/// The digest of the cell the turn wrote `pos` to. +fn committed_digest(turn: &CommittedTurn, pos: i32) -> Result { + let index = u32::try_from(pos)? + .checked_sub(turn.position_start) + .context("a position before the turn")?; + turn.cells + .get(index as usize) + .map(|cell| cell.digest) + .context("a position after the turn") +} + +/// By position, the cell that holds it after the turn and the event that +/// wrote it last, when every ubatch of the turn wrote positions after the +/// last one held, each to a cell no held position used. A removal drops a +/// range of positions: a rejected draft drops the tail of its verify +/// window, which the next window writes again. +/// +/// A copy of the cells written before an event is then what that event +/// read: a later removal below the event's first position either leaves a +/// position of the turn uncomputed, so the turn is not committed, or makes +/// the turn write the event's positions again, so they are not its own. +fn held_cells(turn: &CommittedTurn) -> Option> { + let mut held: BTreeMap = BTreeMap::new(); + let mut cells = BTreeSet::new(); + for (index, event) in turn.events.iter().enumerate() { + let record = match event { + Event::Ubatch(record) => record, + Event::SeqRm { p0, p1 } => { + let dropped: Vec = held.range(removed(*p0, *p1)).map(|(&p, _)| p).collect(); + for pos in dropped { + if let Some((cell, _)) = held.remove(&pos) { + cells.remove(&cell); + } + } + continue; + } + }; + let last = held.keys().next_back().copied(); + for col in (0..record.seq.len()).filter(|&col| record.seq[col] == turn.seq) { + let (pos, cell) = (record.pos[col], record.cell[col]); + if last.is_some_and(|last| pos <= last) + || !u32::try_from(pos).is_ok_and(|p| p >= turn.position_start) + || held.insert(pos, (cell, index)).is_some() + || !cells.insert(cell) + { + return None; + } + } + } + // drafts past the turn's end, which the turn rejected as it stopped, + // were written last, so no replayed ubatch read them + let end = i32::try_from(turn.position_end).ok()?; + held.split_off(&end); + Some(held) +} + +/// Whether a replayed ubatch of `segment` places another sequence's column, +/// which a replay fills with a dummy, in a cell the segment copies. +fn overwrites_a_seeded_cell(turn: &CommittedTurn, segment: &Segment) -> bool { + let copied: BTreeSet = segment.cells.iter().map(|c| c.cell).collect(); + segment + .events + .iter() + .filter_map(|&index| turn.events[index].ubatch()) + .any(|record| { + (0..record.seq.len()) + .any(|col| record.seq[col] != turn.seq && copied.contains(&record.cell[col])) + }) +} diff --git a/crates/skippy-receipts/src/recorder/turn_seed_tests.rs b/crates/skippy-receipts/src/recorder/turn_seed_tests.rs new file mode 100644 index 00000000..1cfd0558 --- /dev/null +++ b/crates/skippy-receipts/src/recorder/turn_seed_tests.rs @@ -0,0 +1,150 @@ +//! Which ubatches a turn replays, and the cells its replay is seeded with, +//! on the test model of `tests.rs`. + +use super::*; + +/// Every replay the replayer ran: the cells it copied and what each of its +/// steps captured. +fn runs(replayer: &FakeReplayer) -> Vec { + replayer.runs.borrow().clone() +} + +#[test] +fn a_long_turn_replays_only_the_ubatches_it_opens() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], false)); + record(&recorder, ubatch(&[(1, 2), (1, 3)], &[2, 3], false)); + record(&recorder, ubatch(&[(1, 4), (1, 5)], &[4, 5], true)); + record(&recorder, ubatch(&[(1, 6)], &[6], true)); + recorder.commit("r1", 1, TurnId::default(), 0..7).unwrap(); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[3, 6])]), &replayer) + .unwrap(); + + // each opened ubatch replays alone, from the cells written before it + assert_eq!( + runs(&replayer), + vec![ + (vec![0, 1], vec![vec![3]]), + (vec![0, 1, 2, 3, 4, 5], vec![vec![6]]), + ] + ); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + assert_eq!(seed.positions(), (0..6).collect::>()); + recorder.check_seed(&seed).unwrap(); +} + +#[test] +fn a_cell_another_sequence_held_is_not_copied_before_the_turn_wrote_it() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + // sequence 3 holds cell 2 when the turn starts, then gives it up, and + // the turn writes there later + record( + &recorder, + ubatch(&[(1, 0), (1, 1), (3, 0)], &[0, 1, 2], true), + ); + recorder.memory_op(MemoryOp::SeqRm, 3, -1, -1, -1); + record(&recorder, ubatch(&[(1, 2)], &[2], true)); + record(&recorder, ubatch(&[(1, 3)], &[3], true)); + recorder.commit("r1", 1, TurnId::default(), 0..4).unwrap(); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[1, 3])]), &replayer) + .unwrap(); + + // the first replay copies nothing, so its dummy column in cell 2 is + // harmless; the second copies cell 2 after the turn wrote it + assert_eq!( + runs(&replayer), + vec![(vec![], vec![vec![1]]), (vec![0, 1, 2], vec![vec![3]])] + ); +} + +/// A turn of seven positions whose serving kept the prefix up to position +/// 4 and dropped the rest. +fn dropped_tail() -> Recorder { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], false)); + record(&recorder, ubatch(&[(1, 2), (1, 3)], &[2, 3], false)); + record(&recorder, ubatch(&[(1, 4), (1, 5)], &[4, 5], true)); + record(&recorder, ubatch(&[(1, 6)], &[6], true)); + recorder.commit("r1", 1, TurnId::default(), 0..7).unwrap(); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, 4, -1); + recorder +} + +#[test] +fn a_turn_whose_dropped_cells_keep_their_rows_copies_them() { + let recorder = dropped_tail(); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[1, 6])]), &replayer) + .unwrap(); + assert_eq!( + runs(&replayer), + vec![ + (vec![], vec![vec![1]]), + (vec![0, 1, 2, 3, 4, 5], vec![vec![6]]) + ] + ); +} + +#[test] +fn a_turn_whose_last_cells_were_reused_replays_from_the_first_reused() { + let recorder = dropped_tail(); + // another request writes cell 4 + record(&recorder, ubatch(&[(2, 0)], &[4], true)); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[1, 6])]), &replayer) + .unwrap(); + // the ubatch of position 1, then everything from the first reused cell + assert_eq!( + runs(&replayer), + vec![ + (vec![], vec![vec![1]]), + (vec![0, 1, 2, 3], vec![vec![], vec![6]]) + ] + ); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + recorder.check_seed(&seed).unwrap(); +} + +#[test] +fn a_turn_with_rejected_drafts_replays_only_the_ubatches_it_opens() { + let recorder = Recorder::new(1, STAGES[1].clone(), "cpu"); + record(&recorder, ubatch(&[(1, 0), (1, 1)], &[0, 1], true)); + // a verify window: the last token and two drafts, the second rejected + record( + &recorder, + ubatch(&[(1, 2), (1, 3), (1, 4)], &[2, 3, 4], true), + ); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, 4, -1); + // the next window writes position 4 again, in another cell + record(&recorder, ubatch(&[(1, 4), (1, 5)], &[5, 4], true)); + recorder.memory_op(MemoryOp::SeqRm, 1, -1, 5, -1); + // the last window: the turn stops at position 5, so its drafts at 6 and + // 7 stay in the cache, past the turn + record( + &recorder, + ubatch(&[(1, 5), (1, 6), (1, 7)], &[4, 6, 7], true), + ); + recorder.commit("r1", 1, TurnId::default(), 0..6).unwrap(); + let replayer = FakeReplayer::for_stage(1); + recorder + .open(&challenge(&[(2, &[3, 4, 5])]), &replayer) + .unwrap(); + + // each window replays alone, from the cells the turn left before it + assert_eq!( + runs(&replayer), + vec![ + (vec![0, 1], vec![vec![3]]), + (vec![0, 1, 2, 3], vec![vec![4]]), + (vec![0, 1, 2, 3, 5], vec![vec![5]]), + ] + ); + let seed = replayer.seed.borrow().clone().expect("a seeded replay"); + recorder.check_seed(&seed).unwrap(); +} diff --git a/crates/skippy-receipts/src/recurrent.rs b/crates/skippy-receipts/src/recurrent.rs new file mode 100644 index 00000000..00f28a8f --- /dev/null +++ b/crates/skippy-receipts/src/recurrent.rs @@ -0,0 +1,312 @@ +//! Client side of the recurrent check, for layers whose token mixing reads +//! a recurrent state (the gated delta net, Mamba's scan, a short +//! convolution). The stage's side is in `recorder::recurrent_opening`. +//! +//! The glue check takes such a layer's mixing outputs as opened, as it does +//! an attention layer's. Here the auditor recomputes them: for the first +//! attention pick of a stage on such a layer, the stage opens the mixing +//! leaves of the ubatch that computed the pick, and of the position after +//! it. The auditor runs the layer's own token-mixing ops, with its +//! llama.cpp, on the opened inputs and the state the ubatch read, and +//! compares the outputs at every position and the state the ops leave with +//! the one the next ubatch read. The comparisons chain: each ubatch's state +//! is the one the ubatch before it left, and the first one is zero. +//! +//! Weights inside the token mixing (a short convolution's kernel, a decay) +//! come from the auditor's GGUF, so a node that ran other weights there +//! fails too. The state a turn started from, when an earlier turn left it, +//! is only bound by the receipt's digest of the exported state. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; +use std::time::Instant; + +use anyhow::{Context, Result, bail, ensure}; + +use crate::attention::opening::AttentionPick; +use crate::binding::verify_mixing_leaf; +use crate::glue::{ + Computed, GlueEvaluator, GlueInput, GlueRequest, GlueValues, GlueVerdict, Verdicts, + blame_refused_values, relative_error, +}; +use crate::layer_tensors::TensorKind; +use crate::node_fault::BlameNode; +use crate::wire::{Challenge, MixingKind, MixingLeafOpening, Receipt, RecurrentOpening}; + +/// A recurrent comparison fails above this error, relative to the largest +/// value of the auditor's vector. The ops sum over every token of the +/// ubatch, and a backend may order the sums differently (in chunks), so +/// this is looser than the glue's. +pub(crate) const RECURRENT_TOLERANCE: f64 = 1e-3; + +/// The attention pick of `challenge` a stage holding `layers` opens the +/// region of: its first on a layer in `state_layers`. +pub fn region_pick<'a>( + challenge: &'a Challenge, + layers: &Range, + state_layers: &BTreeSet, +) -> Option<&'a AttentionPick> { + challenge + .attention + .iter() + .find(|p| layers.contains(&p.layer) && state_layers.contains(&p.layer)) +} + +/// Checks that `opening` is the region of `pick`, and every leaf against +/// the receipt: the ubatch lies in the turn and holds the pick, the leaves +/// run from its first position to the one after it (unless the turn ends +/// there), and a state is opened at both ends and nowhere between. +/// +/// An error is the node's fault ([`crate::node_fault::NodeFault`]). +pub(crate) fn verify_region( + receipt: &Receipt, + pick: &AttentionPick, + opening: &RecurrentOpening, +) -> Result<()> { + region_leaves(receipt, pick, opening).or_node_fault() +} + +fn region_leaves( + receipt: &Receipt, + pick: &AttentionPick, + opening: &RecurrentOpening, +) -> Result<()> { + let RecurrentOpening { + position, + layer, + start, + end, + .. + } = *opening; + ensure!( + position == pick.position && layer == pick.layer, + "the region opens position {position}, layer {layer}, not the pick at position {}, \ + layer {}", + pick.position, + pick.layer + ); + // the node names the ubatch: it must lie in the turn before anything + // is sized by it + ensure!( + receipt.position_start <= start && start < end && end <= receipt.position_end, + "the region {start}..{end} is not positions of the turn {}..{}", + receipt.position_start, + receipt.position_end + ); + ensure!( + (start..end).contains(&position), + "the region {start}..{end} does not hold position {position}" + ); + let continues = end < receipt.position_end; + let wanted = start..end + u32::from(continues); + ensure!( + opening.leaves.len() == wanted.len() + && opening.leaves.iter().map(|l| l.position).eq(wanted.clone()), + "the region opens {} leaves, not one at each position of {wanted:?}", + opening.leaves.len() + ); + for leaf in &opening.leaves { + crate::binding::check_mixing_order(&leaf.mixing) + .with_context(|| format!("position {}", leaf.position))?; + verify_mixing_leaf(receipt, layer, leaf.position, &leaf.mixing, &leaf.path)?; + } + let keys = |leaf: &MixingLeafOpening| -> Vec<(MixingKind, u32)> { + leaf.mixing.iter().map(|t| (t.kind, t.index)).collect() + }; + let first = &opening.leaves[0]; + if let Some(leaf) = opening.leaves.iter().find(|l| keys(l) != keys(first)) { + bail!( + "position {}: the mixing leaf holds other values than at position {start}", + leaf.position + ); + } + ensure!( + first.mixing.iter().any(|t| t.kind == MixingKind::State), + "the region opens no recurrent state" + ); + for leaf in &opening.leaves { + // a ubatch reads its state before its first position + let boundary = leaf.position == start || leaf.position == end; + for state in leaf.mixing.iter().filter(|t| t.kind == MixingKind::State) { + ensure!( + state.values.is_some() == boundary, + "position {}: state {} is {} in the region {start}..{end}", + leaf.position, + state.index, + if boundary { "not opened" } else { "opened" } + ); + } + } + Ok(()) +} + +/// The evaluation of the region: the opened inputs at each position of the +/// ubatch, the states it read, and a zero residual, which the token mixing +/// does not read. `residual_len` is the width of the residual stream. +/// +/// An error is the node's fault: the request is made of the opening alone. +pub(crate) fn region_request( + opening: &RecurrentOpening, + residual_len: usize, +) -> Result { + opened_region(opening, residual_len).or_node_fault() +} + +fn opened_region(opening: &RecurrentOpening, residual_len: usize) -> Result { + let n = usize::try_from(opening.end.saturating_sub(opening.start))?; + let leaves = opening + .leaves + .get(..n) + .context("the region opens too few positions")?; + let positions = leaves + .iter() + .map(|l| i32::try_from(l.position)) + .collect::, _>>()?; + let mut columns: BTreeMap> = BTreeMap::new(); + let mut len: BTreeMap = BTreeMap::new(); + for leaf in leaves { + for input in leaf.mixing.iter().filter(|t| t.kind == MixingKind::Input) { + let values = input.f32_values()?.with_context(|| { + format!( + "position {}: mixing input {} is not opened", + leaf.position, input.index + ) + })?; + let width = *len.entry(input.index).or_insert(values.len()); + ensure!( + width == values.len(), + "mixing input {} changes length", + input.index + ); + columns.entry(input.index).or_default().extend(values); + } + } + let mut inputs: Vec = columns + .into_iter() + .map(|(index, values)| GlueInput { + kind: TensorKind::MixingInput, + index, + len: len[&index], + values: GlueValues::F32(values), + }) + .collect(); + for state in leaves[0] + .mixing + .iter() + .filter(|t| t.kind == MixingKind::State) + { + let values = state + .f32_values()? + .context("the start state is not opened")?; + inputs.push(GlueInput { + kind: TensorKind::MixingState, + index: state.index, + len: values.len(), + values: GlueValues::F32(values), + }); + } + Ok(GlueRequest { + layer: opening.layer, + residual: vec![0.0; residual_len * n], + positions, + inputs, + }) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RegionReport { + pub layer: u32, + pub start: u32, + pub end: u32, + pub verdicts: Vec, + /// Wall time of the auditor's evaluation. + pub eval_seconds: f64, + pub pass: bool, +} + +/// Recomputes the region and compares the outputs at every position, the +/// state left with the one the next ubatch read, and, at the sequence's +/// start, the state read with zero. +pub fn check_region( + evaluator: &dyn GlueEvaluator, + opening: &RecurrentOpening, + residual_len: usize, +) -> Result { + let request = region_request(opening, residual_len)?; + let started = Instant::now(); + let output = evaluator + .evaluate_region(&request) + .map_err(|error| blame_refused_values(error, "recurrent region"))?; + let eval_seconds = started.elapsed().as_secs_f64(); + let computed = Computed::new(&output, opening.layer); + let mut verdicts = Verdicts::default(); + let n = request.positions.len(); + for (col, leaf) in opening.leaves[..n].iter().enumerate() { + for out in leaf.mixing.iter().filter(|t| t.kind == MixingKind::Output) { + let what = format!("position {}: mixing output {}", leaf.position, out.index); + let reference = computed + .get(TensorKind::MixingOutput, out.index) + .and_then(|t| t.f32_column(col)); + let error = match (out.f32_values().or_node_fault()?, reference) { + (Some(opened), Some(reference)) => relative_error(&opened, reference), + _ => f64::INFINITY, + }; + verdicts.add_within("recurrent outputs", &what, error, RECURRENT_TOLERANCE); + } + } + let states = |leaf: &MixingLeafOpening| -> Result)>> { + leaf.mixing + .iter() + .filter(|t| t.kind == MixingKind::State) + .map(|t| { + let values = t.f32_values().or_node_fault()?; + Ok((t.index, values.unwrap_or_default())) + }) + .collect() + }; + if let Some(next) = opening.leaves.get(n) { + for (index, opened) in states(next)? { + let what = format!("position {}: state {index}", next.position); + let error = computed + .get(TensorKind::MixingStateOut, index) + .and_then(|t| t.f32_column(0)) + .map_or(f64::INFINITY, |left| { + relative_error(&opened, most_recent(left, opened.len())) + }); + verdicts.add_within("states left", &what, error, RECURRENT_TOLERANCE); + } + } + if opening.start == 0 { + for (index, read) in states(&opening.leaves[0])? { + let zero = read.iter().all(|&v| v == 0.0); + let what = format!("position 0: state {index}"); + verdicts.add("first state", &what, if zero { 0.0 } else { f64::INFINITY }); + } + } + if verdicts.0.is_empty() { + verdicts.inconsistent("the region compared nothing".into()); + } + let pass = verdicts.0.iter().all(|v| v.pass); + Ok(RegionReport { + layer: opening.layer, + start: opening.start, + end: opening.end, + verdicts: verdicts.0, + eval_seconds, + pass, + }) +} + +/// The most recent state of `left`: an op that keeps rollback snapshots of +/// earlier states for speculative decoding writes them after it. +fn most_recent(left: &[f32], len: usize) -> &[f32] { + if len > 0 && left.len() > len && left.len().is_multiple_of(len) { + &left[..len] + } else { + left + } +} + +#[cfg(test)] +#[path = "recurrent/tests.rs"] +mod tests; diff --git a/crates/skippy-receipts/src/recurrent/tests.rs b/crates/skippy-receipts/src/recurrent/tests.rs new file mode 100644 index 00000000..160c0503 --- /dev/null +++ b/crates/skippy-receipts/src/recurrent/tests.rs @@ -0,0 +1,236 @@ +use super::*; +use crate::glue::{GlueOutput, GlueTensor, StoredRowError}; +use crate::wire::{TensorOpening, encode_f32}; + +/// A toy recurrence: per position, output = state + input, and the state +/// becomes the output. +struct ToyRegion; + +impl GlueEvaluator for ToyRegion { + fn evaluate(&self, _: &GlueRequest) -> Result { + bail!("the toy region has no glue") + } + + fn evaluate_region(&self, request: &GlueRequest) -> Result { + let get = |kind| { + request + .inputs + .iter() + .find(|i| i.kind == kind && i.index == 0) + .map(|i| match &i.values { + GlueValues::F32(v) => v.clone(), + GlueValues::I32(_) => panic!("f32 expected"), + }) + .unwrap() + }; + let inputs = get(TensorKind::MixingInput); + let mut state = get(TensorKind::MixingState); + let mut outputs = Vec::new(); + for x in inputs.chunks(state.len()) { + for (s, x) in state.iter_mut().zip(x) { + *s += x; + } + outputs.extend(&state); + } + let tensor = |kind, values: Vec| GlueTensor { + layer: request.layer, + kind, + index: 0, + flags: 0, + name: String::new(), + len: 2, + values: GlueValues::F32(values), + }; + Ok(GlueOutput { + tensors: vec![ + tensor(TensorKind::MixingOutput, outputs), + tensor(TensorKind::MixingStateOut, state), + ], + unchecked_weights: Vec::new(), + attention: Vec::new(), + }) + } + + fn entry(&self, _: &[i32], _: &[i32]) -> Result> { + bail!("no entry") + } + + fn stored_row_error(&self, _: i32, _: &[u8], _: &[f32]) -> Result { + bail!("no stored rows") + } +} + +fn value(kind: MixingKind, values: Option<[f32; 2]>) -> TensorOpening { + TensorOpening { + kind, + index: 0, + ggml_type: crate::layer_tensors::GGML_F32, + values: values.map(|v| encode_f32(&v)), + } +} + +/// The honest region `start..start + inputs.len()` from `state`, with the +/// leaf after it. +fn region(start: u32, state: [f32; 2], inputs: &[[f32; 2]]) -> RecurrentOpening { + let mut s = state; + let mut leaves = Vec::new(); + for (i, x) in inputs.iter().enumerate() { + let read = (i == 0).then_some(s); + s = [s[0] + x[0], s[1] + x[1]]; + leaves.push(MixingLeafOpening { + position: start + i as u32, + mixing: vec![ + value(MixingKind::Input, Some(*x)), + value(MixingKind::Output, Some(s)), + value(MixingKind::State, read), + ], + path: Vec::new(), + }); + } + let end = start + inputs.len() as u32; + leaves.push(MixingLeafOpening { + position: end, + mixing: vec![ + value(MixingKind::Input, Some([0.0, 0.0])), + value(MixingKind::Output, Some(s)), + value(MixingKind::State, Some(s)), + ], + path: Vec::new(), + }); + RecurrentOpening { + position: start, + layer: 3, + start, + end, + leaves, + } +} + +fn verdict<'a>(report: &'a RegionReport, check: &str) -> &'a GlueVerdict { + report.verdicts.iter().find(|v| v.check == check).unwrap() +} + +#[test] +fn an_honest_region_passes() { + let opening = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0], [0.0, 1.0]]); + let report = check_region(&ToyRegion, &opening, 8).unwrap(); + assert!(report.pass, "{report:?}"); + assert_eq!(verdict(&report, "recurrent outputs").tokens, 3); + assert_eq!(verdict(&report, "states left").tokens, 1); +} + +#[test] +fn the_request_holds_the_inputs_and_the_state_read() { + let opening = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + let request = region_request(&opening, 8).unwrap(); + assert_eq!(request.positions, vec![4, 5]); + assert_eq!(request.residual, vec![0.0; 16]); + let state = request + .inputs + .iter() + .find(|i| i.kind == TensorKind::MixingState) + .unwrap(); + assert_eq!(state.values, GlueValues::F32(vec![1.0, -1.0])); +} + +#[test] +fn a_wrong_output_fails() { + let mut opening = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + opening.leaves[1].mixing[1] = value(MixingKind::Output, Some([9.0, 9.0])); + let report = check_region(&ToyRegion, &opening, 8).unwrap(); + assert!(!report.pass); + assert!(!verdict(&report, "recurrent outputs").pass); +} + +#[test] +fn a_state_the_ubatch_did_not_leave_fails() { + let mut opening = region(4, [1.0, -1.0], &[[0.5, 0.5]]); + opening.leaves[1].mixing[2] = value(MixingKind::State, Some([0.0, 0.0])); + let report = check_region(&ToyRegion, &opening, 8).unwrap(); + assert!(!verdict(&report, "states left").pass); +} + +#[test] +fn a_sequence_starts_from_zero() { + let opening = region(0, [1.0, 0.0], &[[0.5, 0.5]]); + let report = check_region(&ToyRegion, &opening, 8).unwrap(); + assert!(!verdict(&report, "first state").pass); + let opening = region(0, [0.0, 0.0], &[[0.5, 0.5]]); + assert!(check_region(&ToyRegion, &opening, 8).unwrap().pass); +} + +#[test] +fn a_region_outside_the_turn_is_refused_before_it_sizes_anything() { + use crate::node_fault::NodeFault; + // the toy turn computes positions 0..5; the node names the ubatch + let receipt = crate::toy_turn::Turn::new().receipt; + let pick = |position| AttentionPick { + position, + layer: 1, + head_draw: 0, + }; + let named = |position, start, end| RecurrentOpening { + position, + layer: 1, + start, + end, + leaves: Vec::new(), + }; + for (position, start, end) in [ + // four billion positions, which the check used to list + (2, 0, u32::MAX), + (2, 2, 6), + (2, 3, 3), + (2, 4, 1), + (u32::MAX - 1, u32::MAX - 2, u32::MAX), + ] { + let error = + verify_region(&receipt, &pick(position), &named(position, start, end)).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + assert!( + format!("{error:#}").contains("not positions of the turn"), + "{start}..{end}: {error:#}" + ); + } + // inside the turn, the leaves are counted against the ubatch + let error = verify_region(&receipt, &pick(2), &named(2, 0, 3)).unwrap_err(); + assert!(format!("{error:#}").contains("opens 0 leaves"), "{error:#}"); + // and a region of another pick is not this pick's + assert!(verify_region(&receipt, &pick(1), &named(2, 0, 3)).is_err()); +} + +#[test] +fn values_that_are_not_numbers_fail_the_region() { + for bad in [f32::NAN, f32::INFINITY] { + let mut output = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + output.leaves[1].mixing[1] = value(MixingKind::Output, Some([bad, 2.0])); + let report = check_region(&ToyRegion, &output, 8).unwrap(); + assert!(!verdict(&report, "recurrent outputs").pass, "{bad}"); + let mut state = region(4, [1.0, -1.0], &[[0.5, 0.5]]); + state.leaves[1].mixing[2] = value(MixingKind::State, Some([bad, 0.0])); + let report = check_region(&ToyRegion, &state, 8).unwrap(); + assert!(!verdict(&report, "states left").pass, "{bad}"); + } +} + +#[test] +fn a_region_that_makes_no_request_is_the_nodes_fault() { + use crate::node_fault::NodeFault; + // an input the ubatch needs is absent, or changes its length + let mut absent = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + absent.leaves[1].mixing[0] = value(MixingKind::Input, None); + let mut ragged = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + ragged.leaves[1].mixing[0].values = Some(encode_f32(&[1.0])); + let mut short = region(4, [1.0, -1.0], &[[0.5, 0.5], [2.0, 0.0]]); + short.leaves.truncate(1); + for opening in [absent, ragged, short] { + let error = check_region(&ToyRegion, &opening, 8).unwrap_err(); + assert!(NodeFault::find(&error).is_some(), "{error:#}"); + } +} + +#[test] +fn the_most_recent_of_the_snapshots_is_compared() { + assert_eq!(most_recent(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 2), &[1.0, 2.0]); + assert_eq!(most_recent(&[1.0, 2.0, 3.0], 2), &[1.0, 2.0, 3.0]); +} diff --git a/crates/skippy-receipts/src/rounding_profiles.rs b/crates/skippy-receipts/src/rounding_profiles.rs new file mode 100644 index 00000000..558ebfed --- /dev/null +++ b/crates/skippy-receipts/src/rounding_profiles.rs @@ -0,0 +1,190 @@ +//! Which rounding profiles a backend may use for a weight type: the table +//! an audit picks its profiles from ([`crate::audit`]), and the one a +//! stage reads at start to know whether an audit can cover the model it +//! serves. A pair without an entry cannot be checked. + +use anyhow::{Context, Result}; + +use crate::activation_rounding::Profile; + +/// The backends with measured rounding profiles. Metal has none: through +/// `skippy serve`, its prefill outputs differ from every profile by up to +/// 8/10,000, which would fail honest nodes (RECEIPTS_MEASUREMENTS.md, +/// "Detection"). +/// +/// Vulkan has none either. Its integer-dot kernels round K-quant weights +/// in a way no profile models, so an honest node with Q4_K_M weights on +/// an integrated GPU passed 2 of 16 audits, and Q8_0 weights there passed +/// with 1% of margin (RECEIPTS_MEASUREMENTS.md, "Vulkan on the final +/// build"). A stage on a backend without a family issues no receipts, and +/// a receipt that names one is not audited (`coverage`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BackendFamily { + Cpu, + Cuda, +} + +impl BackendFamily { + /// The family of a receipt's backend name, such as `CPU` or `CUDA0`. + pub fn of(backend: &str) -> Option { + if backend.eq_ignore_ascii_case("cpu") { + Some(Self::Cpu) + } else if backend.starts_with("CUDA") { + Some(Self::Cuda) + } else { + None + } + } + + /// [`Self::of`], failing for a backend without rounding profiles. + pub fn checked(backend: &str) -> Result { + Self::of(backend).with_context(|| format!("no rounding profiles for backend {backend} yet")) + } +} + +/// The profiles a backend may use for a weight type. A pair without an +/// entry cannot be checked, which makes the audit unusable rather than +/// letting the most lenient profile decide. +/// +/// The CPU multiplies f16 weights with the f32 activation as it is +/// (`vec_dot_type` of f16 is f32, in `ggml_vec_dot_f16_f32` and the +/// llamafile kernels), and rounds the activation to bf16 for bf16 weights. +/// +/// CUDA picks its kernel by batch size: MMVQ (`Q8DivHalf`) for decode, +/// MMQ (`Q8MulHalf`) for prefill, and a dequantize-and-cuBLAS path that +/// rounds the activation to f16. +/// +/// f16 and bf16 weights on CUDA have none. For f16, decode sums the +/// products in half precision (`mmvf.cu`) and prefill runs cuBLAS with a +/// 16-bit compute type, which no profile of the activation models: an +/// honest node failed every audit, with 278 of 1,120 columns past +/// [`crate::audit`]'s tolerance. bf16 was never measured on CUDA. +/// +/// Q4_1 and Q5_1 have none: their kernels round the product of the weight +/// and activation scales, and the activation block sum, which a profile of +/// the activation alone cannot reproduce (RECEIPTS_MEASUREMENTS.md, "Detection"). +pub fn profiles_for(family: BackendFamily, weight_type: u32) -> Option<&'static [Profile]> { + use crate::ggml_types::{ + GGML_BF16, GGML_F16, GGML_F32, GGML_IQ4_NL, GGML_IQ4_XS, GGML_Q2_K, GGML_Q3_K, GGML_Q4_0, + GGML_Q4_K, GGML_Q5_0, GGML_Q5_K, GGML_Q6_K, GGML_Q8_0, + }; + use Profile::{ + Bf16, CpuQ8, CpuQ8K, F16, Q8DivHalf, Q8Mul64F32, Q8MulF32, Q8MulHalf, Q8MulHalfSums, + Q8MulHalfSumsDp4a, Raw, + }; + let profiles: &'static [Profile] = match (family, weight_type) { + (_, GGML_F32) | (BackendFamily::Cpu, GGML_F16) => &[Raw], + (BackendFamily::Cpu, GGML_BF16) => &[Bf16], + (BackendFamily::Cpu, GGML_Q8_0 | GGML_Q4_0 | GGML_Q5_0 | GGML_IQ4_NL) => &[CpuQ8], + ( + BackendFamily::Cpu, + GGML_Q2_K | GGML_Q3_K | GGML_Q4_K | GGML_Q5_K | GGML_Q6_K | GGML_IQ4_XS, + ) => &[CpuQ8K], + (BackendFamily::Cuda, GGML_Q8_0) => &[Q8DivHalf, Q8MulHalf, F16], + (BackendFamily::Cuda, GGML_Q4_0) => &[Q8DivHalf, Q8MulHalf, F16], + (BackendFamily::Cuda, GGML_Q4_K | GGML_Q5_K) => { + &[Q8DivHalf, Q8MulHalfSums, Q8MulHalfSumsDp4a, F16] + } + (BackendFamily::Cuda, GGML_Q5_0 | GGML_Q3_K | GGML_Q6_K | GGML_IQ4_NL | GGML_IQ4_XS) => { + &[Q8DivHalf, Q8MulF32, F16] + } + (BackendFamily::Cuda, GGML_Q2_K) => &[Q8DivHalf, Q8Mul64F32, F16], + _ => return None, + }; + Some(profiles) +} + +/// Why no audit can check a stage on `family` that multiplies `tensors` +/// (name and GGML type), if one of them has a type without profiles. +pub fn unprofiled<'a>( + family: BackendFamily, + tensors: impl IntoIterator, +) -> Option { + let (name, ggml_type) = tensors + .into_iter() + .find(|(_, ggml_type)| profiles_for(family, *ggml_type).is_none())?; + Some(format!( + "no rounding profile for {} weights ({name}) on {family:?}", + crate::ggml_types::type_name(ggml_type) + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ggml_types::{ + GGML_BF16, GGML_F16, GGML_F32, GGML_Q2_K, GGML_Q4_1, GGML_Q4_K, GGML_Q8_0, + }; + + #[test] + fn each_backend_names_its_own_profiles() { + assert_eq!(BackendFamily::of("CPU"), Some(BackendFamily::Cpu)); + assert_eq!(BackendFamily::of("CUDA0"), Some(BackendFamily::Cuda)); + // a backend without measured profiles has no family: Vulkan's kernels + // round in ways no profile models, and Metal's prefill fits none + for unprofiled in ["Vulkan0", "Vulkan1", "MTL0", "Metal", "ROCm0", ""] { + assert_eq!(BackendFamily::of(unprofiled), None, "{unprofiled}"); + assert!(BackendFamily::checked(unprofiled).is_err()); + } + assert_eq!( + profiles_for(BackendFamily::Cpu, GGML_Q8_0), + Some(&[Profile::CpuQ8][..]) + ); + // CUDA's q8 kernels, never the CPU one + let cuda = profiles_for(BackendFamily::Cuda, GGML_Q8_0).unwrap(); + assert!(!cuda.contains(&Profile::CpuQ8) && !cuda.contains(&Profile::Raw)); + assert_eq!( + profiles_for(BackendFamily::Cpu, GGML_F32), + Some(&[Profile::Raw][..]) + ); + // the CPU kernels take the f32 activation of f16 weights as it is + assert_eq!( + profiles_for(BackendFamily::Cpu, GGML_F16), + Some(&[Profile::Raw][..]) + ); + assert_eq!( + profiles_for(BackendFamily::Cpu, GGML_BF16), + Some(&[Profile::Bf16][..]) + ); + // the CPU quantizes K-quant activations per 256, CUDA per 32 or 64 + assert_eq!( + profiles_for(BackendFamily::Cpu, GGML_Q4_K), + Some(&[Profile::CpuQ8K][..]) + ); + assert!( + profiles_for(BackendFamily::Cuda, GGML_Q2_K) + .unwrap() + .contains(&Profile::Q8Mul64F32) + ); + // types without a reference dequantization or a known profile have none + assert_eq!(profiles_for(BackendFamily::Cpu, 19), None); + assert_eq!(profiles_for(BackendFamily::Cuda, GGML_Q4_1), None); + } + + /// CUDA sums f16 products in half precision and runs cuBLAS with a + /// 16-bit compute type, which no profile models: an honest node failed + /// every audit. bf16 was never measured there. + #[test] + fn cuda_has_no_profile_for_16_bit_float_weights() { + for weight_type in [GGML_F16, GGML_BF16] { + assert_eq!(profiles_for(BackendFamily::Cuda, weight_type), None); + } + } + + #[test] + fn the_first_unprofiled_tensor_is_named() { + let tensors = [ + ("blk.0.attn_q.weight", GGML_Q8_0), + ("blk.0.attn_k.weight", GGML_F16), + ("blk.0.attn_v.weight", GGML_Q4_1), + ]; + assert_eq!(unprofiled(BackendFamily::Cpu, tensors[..2].to_vec()), None); + let cpu = unprofiled(BackendFamily::Cpu, tensors.to_vec()).unwrap(); + assert!(cpu.contains("q4_1 weights (blk.0.attn_v.weight)"), "{cpu}"); + let cuda = unprofiled(BackendFamily::Cuda, tensors.to_vec()).unwrap(); + assert!( + cuda.contains("f16 weights (blk.0.attn_k.weight) on Cuda"), + "{cuda}" + ); + } +} diff --git a/crates/skippy-receipts/src/sampler_request.rs b/crates/skippy-receipts/src/sampler_request.rs new file mode 100644 index 00000000..c86c56a9 --- /dev/null +++ b/crates/skippy-receipts/src/sampler_request.rs @@ -0,0 +1,365 @@ +//! What a client asked the sampler for, against what the node says it ran. +//! +//! A receipt's sampler statement is the node's own text +//! ([`crate::turn::TurnBinding::sampler`]), and it decides how the head +//! check judges the turn's tokens ([`crate::head::sampling`]): a grammar, a +//! penalty or a sampler the check does not know leaves them unjudged, a +//! logit bias moves any token into the candidates, a chain without filters +//! keeps every token, and a statement that names no draw leaves the draw +//! unreplayed. A node that wrote tokens of its own choosing would state one +//! of those. So a client compares the statement with the request it sent: +//! a parameter it set must be stated with its exact value and applied, and +//! nothing that leaves the tokens or the draw unjudged may be stated +//! unless the request asked for it ([`crate::head::sampling::Gap`]). +//! +//! The request is not part of a receipt, so a contradiction convinces only +//! the client that sent it: it is a failure no evidence shows. A recheck of +//! evidence has no request, and reads the statement leniently: what the +//! statement leaves unjudged stays so, with a note. +//! +//! The seed is such a parameter: a node that names a draw a client can +//! replay ([`crate::head::draw`]) is held to the token the stated seed +//! picks, so a client that set the seed knows the node did not choose it. +//! +//! What stays open: a parameter the client left unset takes the node's +//! default, which the client knows only as far as +//! [`RequestedSampling::unset_filters_on`] says. + +use serde_json::Value; + +use crate::head::sampling::{self, Gap}; +use crate::turn; + +/// The sampling parameters of a client's request. A field is `None` when +/// the request did not set it, or the caller does not know. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RequestedSampling { + pub temperature: Option, + pub top_p: Option, + pub top_k: Option, + pub min_p: Option, + /// The seed the request set, in its body or in its receipt request + /// (`x-receipt-seed`). A seed of 0 asks for a random one, like none. + pub seed: Option, + /// Reasoning tokens the request allowed; negative for no limit. + pub reasoning_budget: Option, + /// Whether the request carried a grammar, or a response format or + /// tools that make one. + pub grammar: Option, + /// Whether the request set a penalty (repeat, presence, frequency, + /// DRY) or another sampler beyond temperature, top-k, top-p and min-p + /// (typical-p, top-n-sigma, XTC, mirostat, a dynamic temperature). + pub penalties: Option, + /// Whether the request carried logit biases. + pub logit_bias: Option, + /// Whether the request named its own sampler chain (`samplers` or + /// `sampler_sequence`). Without one, the node runs its default chain, + /// which holds every filter. + pub sampler_chain: Option, + /// Whether the request asked the node to ignore the end of generation + /// (`ignore_eos`). + pub ignore_eos: Option, + /// Whether a filter the request left unset (top-k, top-p, min-p) runs + /// at a default that is on, as Skippy's are (top-k 40, top-p 0.95, + /// min-p 0.05). A node whose operator configured a default that turns + /// a filter off states it off, which then contradicts the request. + pub unset_filters_on: Option, +} + +/// The ranges Skippy's request validation allows, so an honest node states +/// no value outside them (`sampling_config` in +/// `skippy-serving/src/frontend/request.rs`). +const RANGES: [(&str, f64, f64); 5] = [ + ("temperature", 0.0, 100.0), + ("top_p", 0.0, 1.0), + ("min_p", 0.0, 1.0), + ("typical_p", 0.0, 1.0), + ("dynatemp_range", 0.0, f64::MAX), +]; + +impl RequestedSampling { + /// A request for the best logit at every token, with nothing that + /// could change the choice: what `skippy audit-receipt` sends. + pub fn greedy() -> Self { + Self { + temperature: Some(0.0), + reasoning_budget: Some(-1), + grammar: Some(false), + penalties: Some(false), + logit_bias: Some(false), + sampler_chain: Some(false), + ignore_eos: Some(false), + ..Self::default() + } + } + + /// The seed the request fixed. A node asked for no seed, or for seed 0, + /// chooses its own. + pub fn client_seed(&self) -> Option { + self.seed.filter(|seed| *seed != 0) + } + + /// How `statement`, a receipt's sampler statement, contradicts the + /// request; `None` when it does not. + pub fn contradiction(&self, statement: &str) -> Option { + if statement == turn::GREEDY { + return self.against_greedy(); + } + let Some(stated) = turn::sampler_parameters(statement).filter(Value::is_object) else { + return Some("the sampler statement is neither greedy nor a list of parameters".into()); + }; + let gaps = match sampling::gaps(&stated) { + Ok(gaps) => gaps, + Err(malformed) => { + return Some(format!("the sampler statement is malformed: {malformed}")); + } + }; + against_range(&stated) + .or_else(|| self.against_values(&stated)) + .or_else(|| self.against_budget(&stated)) + .or_else(|| self.against_chain(&stated)) + .or_else(|| self.against_unset_filters(&stated)) + .or_else(|| self.against_gaps(&gaps)) + .or_else(|| self.against_constraints(&stated)) + } + + /// A request the node decodes greedily however it states its sampler: + /// a temperature of 0, or every filter turned off at a temperature of 1 + /// with no seed, which Skippy reads as sampling turned off. + fn decodes_greedily(&self) -> bool { + let Some(temperature) = self.temperature else { + return false; + }; + temperature <= 0.0 + || (same(temperature, 1.0) + && self.top_p.is_some_and(|p| p >= 1.0) + && self.top_k == Some(0) + && self.min_p.is_some_and(|p| p <= 0.0)) + } + + /// A node decodes greedily at a temperature of 0, and when a request + /// turns every filter off at a temperature of 1. + fn against_greedy(&self) -> Option { + let temperature = self.temperature.filter(|t| *t > 0.0)?; + (!self.decodes_greedily()).then(|| { + format!("the request set temperature {temperature}; the node says it decoded greedily") + }) + } + + /// Every parameter the request set is stated with its exact value: the + /// node holds the numbers as f32, and the seed and top-k as integers. + fn against_values(&self, stated: &Value) -> Option { + let numbers = [ + ("temperature", self.temperature), + ("top_p", self.top_p), + ("min_p", self.min_p), + ]; + for (name, asked) in numbers { + let Some(asked) = asked else { continue }; + match stated[name].as_f64() { + Some(value) if same(value, asked) => {} + // a request the runtime decodes greedily runs at 0 + Some(0.0) if name == "temperature" && self.decodes_greedily() => {} + Some(value) => { + return Some(format!( + "the request set {name} {asked}; the node says {value}" + )); + } + None => return Some(format!("the request set {name}; the node states none")), + } + } + let integers = [ + ("top_k", self.top_k), + ("seed", self.client_seed().map(|s| s as i64)), + ]; + for (name, asked) in integers { + let Some(asked) = asked else { continue }; + match stated[name].as_i64() { + Some(value) if value == asked => {} + Some(value) => { + return Some(format!( + "the request set {name} {asked}; the node says {value}" + )); + } + None => return Some(format!("the request set {name}; the node states none")), + } + } + None + } + + /// The stated reasoning budget is at most the one the request allowed. + fn against_budget(&self, stated: &Value) -> Option { + let budget = stated["reasoning_budget"].as_i64(); + match (self.reasoning_budget, budget) { + (Some(asked), Some(stated)) if asked < 0 || stated > asked => Some(format!( + "the request allowed {} reasoning tokens; the node says it allowed {stated}", + if asked < 0 { + "any number of".to_owned() + } else { + asked.to_string() + } + )), + (Some(asked), None) if asked >= 0 => Some(format!( + "the request allowed {asked} reasoning tokens; the node states no limit" + )), + _ => None, + } + } + + /// The filters the request turned on, or left at a default that is on. + fn filters_on(&self) -> [(&'static str, bool); 3] { + let unset_on = self.unset_filters_on == Some(true); + [ + ("top_k", self.top_k.map_or(unset_on, |k| k > 0)), + ("top_p", self.top_p.map_or(unset_on, |p| p < 1.0)), + ("min_p", self.min_p.map_or(unset_on, |p| p > 0.0)), + ] + } + + /// A filter the request turned on is in the chain the node says it + /// ran, when the request left the chain to the node. A chain without + /// its filters keeps every token. + fn against_chain(&self, stated: &Value) -> Option { + if self.sampler_chain != Some(false) { + return None; + } + let chain = stated_chain(stated); + let missing = self + .filters_on() + .into_iter() + .find(|(name, on)| *on && !chain.iter().any(|c| c == name)) + .map(|(name, _)| name); + let temperature = self.temperature.is_some() + && !chain + .iter() + .any(|name| ["temperature", "temp"].contains(&name.as_str())); + missing + .or(temperature.then_some("temperature")) + .map(|name| format!("the request set {name}; the node's sampler chain leaves it out")) + } + + /// A filter the request left at a default that is on is not stated off. + fn against_unset_filters(&self, stated: &Value) -> Option { + if self.unset_filters_on != Some(true) { + return None; + } + let off = [ + ( + "top_k", + self.top_k.is_none() && stated["top_k"].as_i64().is_some_and(|k| k <= 0), + ), + ( + "top_p", + self.top_p.is_none() && stated["top_p"].as_f64().is_some_and(|p| p >= 1.0), + ), + ( + "min_p", + self.min_p.is_none() && stated["min_p"].as_f64().is_some_and(|p| p <= 0.0), + ), + ]; + off.into_iter() + .find(|(_, off)| *off) + .map(|(name, _)| format!("the request left {name} on; the node says it was off")) + } + + /// What leaves the tokens or the draw unjudged is something the + /// request asked for. + fn against_gaps(&self, gaps: &[Gap]) -> Option { + gaps.iter().find(|gap| self.unexplained(gap)).map(|gap| { + format!( + "the node says {}; the request asked for no such thing", + gap.describe() + ) + }) + } + + /// Whether the request leaves `gap` unexplained. + fn unexplained(&self, gap: &Gap) -> bool { + match gap { + Gap::Grammar => self.grammar == Some(false), + Gap::Mirostat | Gap::Sampler(_) | Gap::DynamicTemperature => { + self.penalties == Some(false) + } + Gap::Unknown(_) => self.sampler_chain == Some(false) || self.penalties == Some(false), + // a node that issues a receipt for a turn that draws names the + // draw it replays + Gap::NoDraw => true, + } + } + + /// Nothing the request did not send is claimed. + fn against_constraints(&self, stated: &Value) -> Option { + let unsent = |what: &str| format!("the node says {what}; the request sent none"); + let biased = stated["logit_bias"] + .as_array() + .is_some_and(|b| !b.is_empty()); + if self.logit_bias == Some(false) && biased { + return Some(unsent("logit biases moved the tokens")); + } + let ignores_end = stated["ignore_eos"].as_bool() == Some(true); + if self.ignore_eos == Some(false) && ignores_end { + return Some(unsent("the turn ignored its end")); + } + // the runtime builds a reasoning sampler only for a turn with a + // finite budget, with or without a grammar (`reasoning_sampler` in + // skippy-serving); the budget itself is held against the request + // by `against_budget` + let budgeted = stated["reasoning_budget"].as_i64().is_some_and(|b| b >= 0); + if !stated[turn::REASONING].is_null() && !budgeted { + return Some( + "the node says a reasoning sampler forced tokens; it states no reasoning budget" + .to_owned(), + ); + } + None + } +} + +/// The names of the chain a statement says it ran, the runtime's default +/// chain for an empty one. +fn stated_chain(stated: &Value) -> Vec { + let names: Vec = stated["samplers"] + .as_array() + .map(|names| { + names + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + if !names.is_empty() { + return names; + } + let number = |key: &str, default: f64| stated[key].as_f64().unwrap_or(default); + sampling::default_chain(number("typical_p", 1.0), number("top_p", 1.0)) + .into_iter() + .map(str::to_owned) + .collect() +} + +/// A stated value outside the range a request may set. +fn against_range(stated: &Value) -> Option { + let outside = RANGES.into_iter().find_map(|(name, low, high)| { + let value = stated[name].as_f64()?; + (!(low..=high).contains(&value)) + .then(|| format!("the stated {name} {value} is out of range")) + }); + let top_k = stated["top_k"] + .as_i64() + .filter(|k| *k < 0) + .map(|k| format!("the stated top_k {k} is out of range")); + let mode = stated["mirostat"]["mode"] + .as_i64() + .filter(|m| !(0..=2).contains(m)) + .map(|m| format!("the stated mirostat mode {m} is out of range")); + outside.or(top_k).or(mode) +} + +/// Whether a stated value is the one asked: the node holds both as f32. +fn same(stated: f64, asked: f64) -> bool { + stated as f32 == asked as f32 +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/sampler_request/tests.rs b/crates/skippy-receipts/src/sampler_request/tests.rs new file mode 100644 index 00000000..d4d54106 --- /dev/null +++ b/crates/skippy-receipts/src/sampler_request/tests.rs @@ -0,0 +1,396 @@ +use super::*; + +/// A statement of the node's default chain, with `overrides`. +fn statement(overrides: serde_json::Value) -> String { + let mut p = serde_json::json!({ + "seed": 0, + "draw": "indexed-v1", + "samplers": ["penalties", "dry", "top_n_sigma", "top_k", "typical_p", "top_p", "min_p", "xtc", "temperature"], + "temperature": 0.800000011920929, + "dynatemp_range": 0.0, + "top_k": 40, + "top_p": 0.949999988079071, + "min_p": 0.05000000074505806, + "typical_p": 1.0, + "top_nsigma": -1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "repeat_penalty": 1.0, + "dry": { "multiplier": 0.0 }, + "xtc": { "probability": 0.0, "threshold": 0.1 }, + "mirostat": { "mode": 0 }, + "logit_bias": [], + "grammar": null, + "reasoning_budget": null, + }); + for (k, v) in overrides.as_object().unwrap() { + p[k] = v.clone(); + } + turn::sampled(&p) +} + +/// A request that set these parameters and sent no constraint. +fn plain(temperature: f64, top_p: f64, top_k: i64, min_p: f64) -> RequestedSampling { + RequestedSampling { + temperature: Some(temperature), + top_p: Some(top_p), + top_k: Some(top_k), + min_p: Some(min_p), + grammar: Some(false), + penalties: Some(false), + logit_bias: Some(false), + sampler_chain: Some(false), + ..RequestedSampling::default() + } +} + +#[test] +fn a_statement_of_what_the_request_set_is_consistent() { + // the node holds the values as f32 + let request = plain(0.8, 0.95, 40, 0.05); + assert_eq!( + request.contradiction(&statement(serde_json::json!({}))), + None + ); + let seeded = RequestedSampling { + seed: Some(7), + ..request + }; + assert_eq!( + seeded.contradiction(&statement(serde_json::json!({"seed": 7}))), + None + ); + // a request that set nothing is contradicted by nothing it could know + let unknown = RequestedSampling::default(); + for overrides in [ + serde_json::json!({}), + serde_json::json!({"temperature": 1.5, "grammar": "abc", "logit_bias": [[1, 9.0]]}), + ] { + assert_eq!(unknown.contradiction(&statement(overrides)), None); + } + assert_eq!(unknown.contradiction(turn::GREEDY), None); +} + +#[test] +fn a_parameter_the_request_set_must_be_stated_with_its_value() { + let request = RequestedSampling { + seed: Some(7), + ..plain(0.8, 0.95, 40, 0.05) + }; + for (overrides, named) in [ + ( + serde_json::json!({"seed": 7, "temperature": 1.5}), + "temperature", + ), + (serde_json::json!({"seed": 7, "top_p": 1.0}), "top_p"), + (serde_json::json!({"seed": 7, "top_k": 0}), "top_k"), + (serde_json::json!({"seed": 7, "min_p": 0.0}), "min_p"), + (serde_json::json!({"seed": 8}), "seed"), + (serde_json::json!({"seed": 7, "top_k": null}), "top_k"), + ] { + let found = request.contradiction(&statement(overrides.clone())); + assert!( + found.as_deref().is_some_and(|f| f.contains(named)), + "{overrides}: {found:?}" + ); + } +} + +#[test] +fn a_constraint_the_request_did_not_send_must_not_be_claimed() { + // each of these leaves the tokens unjudged, or moves any token into + // the candidates + let request = plain(0.8, 0.95, 40, 0.05); + for overrides in [ + serde_json::json!({"grammar": "9f2c"}), + serde_json::json!({"logit_bias": [[5, 100.0]]}), + serde_json::json!({"repeat_penalty": 1.1}), + serde_json::json!({"presence_penalty": 0.5}), + serde_json::json!({"dry": {"multiplier": 0.8}}), + serde_json::json!({"xtc": {"probability": 0.5, "threshold": 0.1}}), + serde_json::json!({"typical_p": 0.5}), + serde_json::json!({"top_nsigma": 2.0}), + serde_json::json!({"mirostat": {"mode": 2}}), + serde_json::json!({"dynatemp_range": 0.5}), + serde_json::json!({"samplers": ["top_k", "top_p", "min_p", "mystery", "temperature"]}), + ] { + let found = request.contradiction(&statement(overrides.clone())); + assert!(found.is_some(), "{overrides} was accepted"); + } + // a request that did send them is not contradicted + let constrained = RequestedSampling { + grammar: Some(true), + penalties: Some(true), + logit_bias: Some(true), + ..request + }; + let overrides = serde_json::json!({ + "grammar": "9f2c", "logit_bias": [[5, 1.0]], "repeat_penalty": 1.1, + }); + assert_eq!(constrained.contradiction(&statement(overrides)), None); +} + +#[test] +fn a_chain_that_leaves_out_a_filter_the_request_set_is_a_contradiction() { + // without its filters, a chain keeps every token + let request = plain(0.8, 0.95, 40, 0.05); + for chain in [ + serde_json::json!(["temperature"]), + serde_json::json!(["top_k", "top_p", "temperature"]), + serde_json::json!(["top_k", "top_p", "min_p"]), + ] { + let found = request.contradiction(&statement(serde_json::json!({"samplers": chain}))); + assert!( + found + .as_deref() + .is_some_and(|f| f.contains("leaves it out")), + "{chain}: {found:?}" + ); + } + // an empty chain is the runtime's default chain, which holds them + assert_eq!( + request.contradiction(&statement(serde_json::json!({"samplers": []}))), + None + ); + // a request that named its own chain decides what is in it + let own = RequestedSampling { + sampler_chain: Some(true), + ..request + }; + let chain = serde_json::json!({"samplers": ["top_k", "temperature"]}); + assert_eq!(own.contradiction(&statement(chain)), None); +} + +#[test] +fn a_greedy_statement_fits_a_request_that_asked_for_the_best_token() { + assert_eq!( + RequestedSampling::greedy().contradiction(turn::GREEDY), + None + ); + // a request that turned every filter off at a temperature of 1 is + // decoded greedily too + assert_eq!(plain(1.0, 1.0, 0, 0.0).contradiction(turn::GREEDY), None); + let found = plain(0.8, 0.95, 40, 0.05).contradiction(turn::GREEDY); + assert!(found.is_some_and(|f| f.contains("greedily"))); + assert!( + plain(1.0, 0.95, 0, 0.0) + .contradiction(turn::GREEDY) + .is_some() + ); +} + +#[test] +fn the_audit_request_accepts_only_an_unconstrained_best_token() { + let asked = RequestedSampling::greedy(); + // a node whose model thinks within a budget says so; the audit asked + // for none + let budget = statement(serde_json::json!({"temperature": 0.0, "reasoning_budget": 512})); + assert!(asked.contradiction(&budget).is_some()); + for overrides in [ + serde_json::json!({"temperature": 0.7}), + serde_json::json!({"temperature": 0.0, "repeat_penalty": 1.1}), + serde_json::json!({"temperature": 0.0, "grammar": "9f2c"}), + serde_json::json!({"temperature": 0.0, "logit_bias": [[1, 5.0]]}), + serde_json::json!({"temperature": 0.0, "samplers": ["top_k"]}), + ] { + let found = asked.contradiction(&statement(overrides.clone())); + assert!(found.is_some(), "{overrides} was accepted"); + } + assert_eq!( + asked.contradiction(&statement(serde_json::json!({"temperature": 0.0}))), + None + ); +} + +#[test] +fn a_default_reasoning_budget_does_not_contradict_a_request_that_named_none() { + // The known honest case: a thinking model gets a default budget from + // the server, so a request at temperature 0 without `reasoning_budget` + // is not greedy, and its statement names the budget. + let request = RequestedSampling { + temperature: Some(0.0), + grammar: Some(false), + penalties: Some(false), + logit_bias: Some(false), + sampler_chain: Some(false), + ..RequestedSampling::default() + }; + let honest = statement(serde_json::json!({"temperature": 0.0, "reasoning_budget": 2048})); + assert_eq!(request.contradiction(&honest), None); + // a request that named a budget is held to it + let limited = RequestedSampling { + reasoning_budget: Some(1024), + ..request.clone() + }; + assert!(limited.contradiction(&honest).is_some()); + let within = statement(serde_json::json!({"temperature": 0.0, "reasoning_budget": 512})); + assert_eq!(limited.contradiction(&within), None); + let unlimited = statement(serde_json::json!({"temperature": 0.0})); + assert!(limited.contradiction(&unlimited).is_some()); +} + +#[test] +fn a_statement_that_names_nothing_is_a_contradiction() { + let request = RequestedSampling::default(); + for text in ["sampled", "sampled {", "whatever the node likes", ""] { + assert!(request.contradiction(text).is_some(), "{text:?}"); + } +} + +#[test] +fn a_node_may_not_opt_out_of_the_judgement_unasked() { + let request = RequestedSampling { + ignore_eos: Some(false), + ..plain(0.8, 0.95, 40, 0.05) + }; + for (overrides, named) in [ + // no draw a client can replay, on a turn that draws + (serde_json::json!({"draw": null}), "no draw"), + (serde_json::json!({"draw": "another-rule"}), "no draw"), + // end tokens the request did not ask to ignore + (serde_json::json!({"ignore_eos": true}), "ignored its end"), + // a reasoning sampler with no budget that could force a token + ( + serde_json::json!({"reasoning": {"start": "", "ends": [""]}}), + "no reasoning budget", + ), + // a statement malformed in itself + (serde_json::json!({"reasoning": 1}), "malformed"), + (serde_json::json!({"top_k": 5_000_000_000u64}), "malformed"), + // a value no request can set + (serde_json::json!({"temperature": 150.0}), "out of range"), + (serde_json::json!({"top_p": -0.5}), "out of range"), + ] { + let found = request.contradiction(&statement(overrides.clone())); + assert!( + found.as_deref().is_some_and(|f| f.contains(named)), + "{overrides}: {found:?}" + ); + } + // a request that asked for them is not contradicted + let asked = RequestedSampling { + ignore_eos: Some(true), + grammar: Some(true), + ..request + }; + let overrides = serde_json::json!({ + "ignore_eos": true, "grammar": "9f2c", "reasoning_budget": 8, + "reasoning": {"start": "", "ends": [""]}, + }); + assert_eq!(asked.contradiction(&statement(overrides)), None); +} + +// The runtime builds the reasoning sampler for every turn with a finite +// budget, with a grammar or without. A thinking model's node sets a +// default budget, so a request that named none can get one. +#[test] +fn a_reasoning_sampler_needs_a_budget_and_no_grammar() { + let sampler = serde_json::json!({"start": "", "ends": [""]}); + let stated = |budget: serde_json::Value| { + statement(serde_json::json!({"reasoning_budget": budget, "reasoning": sampler})) + }; + // the request named no budget: the node's default is consistent + let unset = plain(0.8, 0.95, 40, 0.05); + assert_eq!(unset.reasoning_budget, None); + assert_eq!(unset.contradiction(&stated(8.into())), None); + assert_eq!(unset.contradiction(&stated(0.into())), None); + // the request named one: the node may not allow more + let asked = RequestedSampling { + reasoning_budget: Some(8), + ..plain(0.8, 0.95, 40, 0.05) + }; + assert_eq!(asked.contradiction(&stated(8.into())), None); + assert!(asked.contradiction(&stated(64.into())).is_some()); + // the request allowed any number: no sampler can force a token + let unlimited = RequestedSampling { + reasoning_budget: Some(-1), + ..plain(0.8, 0.95, 40, 0.05) + }; + assert!(unlimited.contradiction(&stated(8.into())).is_some()); + // a sampler with no budget, or a negative one, forces nothing + for budget in [serde_json::Value::Null, (-1).into()] { + let found = unset.contradiction(&stated(budget.clone())); + assert!( + found + .as_deref() + .is_some_and(|f| f.contains("no reasoning budget")), + "{budget}: {found:?}" + ); + } +} + +#[test] +fn numbers_are_compared_exactly() { + // a seed near 2^31 and its neighbour are two seeds + let request = RequestedSampling { + seed: Some(2_147_483_648), + ..plain(0.8, 0.95, 40, 0.05) + }; + let found = request.contradiction(&statement(serde_json::json!({"seed": 2_147_483_649u64}))); + assert!(found.is_some_and(|f| f.contains("seed"))); + assert_eq!( + request.contradiction(&statement(serde_json::json!({"seed": 2_147_483_648u64}))), + None + ); + // the node holds a temperature as an f32: the same f32 is the same + // value, the next one is not + let warm = plain(0.7, 0.95, 40, 0.05); + let as_f32 = f64::from(0.7f32); + assert_eq!( + warm.contradiction(&statement(serde_json::json!({"temperature": as_f32}))), + None + ); + let next = f64::from(f32::from_bits(0.7f32.to_bits() + 1)); + assert!( + warm.contradiction(&statement(serde_json::json!({"temperature": next}))) + .is_some() + ); +} + +#[test] +fn a_filter_left_at_a_default_that_is_on_is_not_stated_off() { + let request = RequestedSampling { + temperature: Some(0.8), + grammar: Some(false), + penalties: Some(false), + logit_bias: Some(false), + sampler_chain: Some(false), + unset_filters_on: Some(true), + ..RequestedSampling::default() + }; + assert_eq!( + request.contradiction(&statement(serde_json::json!({}))), + None + ); + for overrides in [ + serde_json::json!({"top_k": 0}), + serde_json::json!({"top_p": 1.0}), + serde_json::json!({"min_p": 0.0}), + serde_json::json!({"samplers": ["top_k", "temperature"]}), + ] { + let found = request.contradiction(&statement(overrides.clone())); + assert!(found.is_some(), "{overrides}"); + } + // a caller that does not know the defaults holds the node to nothing + let unknown = RequestedSampling { + unset_filters_on: None, + ..request + }; + assert_eq!( + unknown.contradiction(&statement(serde_json::json!({"top_k": 0}))), + None + ); +} + +#[test] +fn a_request_with_sampling_off_may_be_stated_at_a_temperature_of_zero() { + // Skippy turns sampling off for a request at temperature 1 with every + // filter off, and the runtime then keeps the best logit + let off = plain(1.0, 1.0, 0, 0.0); + let budgeted = statement(serde_json::json!({ + "temperature": 0.0, "top_p": 1.0, "top_k": 0, "min_p": 0.0, + "draw": null, "reasoning_budget": 16, + })); + assert_eq!(off.contradiction(&budgeted), None); + assert!(plain(0.9, 1.0, 0, 0.0).contradiction(&budgeted).is_some()); +} diff --git a/crates/skippy-receipts/src/shards.rs b/crates/skippy-receipts/src/shards.rs new file mode 100644 index 00000000..a41a69f1 --- /dev/null +++ b/crates/skippy-receipts/src/shards.rs @@ -0,0 +1,235 @@ +//! A split GGUF (`name-00001-of-00003.gguf` and its siblings) read as one +//! file: the shards' bytes end to end. Each shard has its own header and +//! the tensors it holds; [`WeightFile::open_shards`] reads them all and +//! places each tensor at its offset in the whole. +//! +//! The name of the first shard says how many there are, and a node chooses +//! the name: more than [`MAX_SHARDS`] is refused before any is opened. +//! +//! [`WeightFile::open_shards`]: crate::weights::WeightFile::open_shards + +use anyhow::{Context, Result, bail}; + +use crate::weights::ByteSource; +use crate::weights::limits::{MAX_SHARDS, refuse}; + +/// The shards of a split GGUF, end to end. +pub(crate) struct Shards { + /// Each shard with the offset of its first byte in the whole. + parts: Vec<(u64, Box)>, + size: u64, +} + +impl Shards { + pub fn new(shards: Vec>) -> Result { + let mut size = 0u64; + let mut parts = Vec::with_capacity(shards.len()); + for shard in shards { + let base = size; + size = size + .checked_add(shard.size()) + .context("the shards are larger than any file")?; + parts.push((base, shard)); + } + Ok(Self { parts, size }) + } + + /// Each shard and the offset of its first byte in the whole. + pub fn parts(&self) -> impl Iterator { + self.parts + .iter() + .map(|(base, shard)| (*base, shard.as_ref())) + } + + /// The pieces of `[offset, offset + len)` in each shard: the shard's + /// index, the offset in the shard, and the length. + fn pieces(&self, offset: u64, len: u64) -> Result> { + let end = offset.saturating_add(len); + if end > self.size { + bail!("bytes {offset}..{end} are past the end of the shards"); + } + Ok(self + .parts + .iter() + .enumerate() + .filter_map(|(index, (base, shard))| { + let start = offset.max(*base); + // the shards' sizes sum to `size`, so this does not wrap + let stop = end.min(base + shard.size()); + (start < stop).then(|| (index, start - base, stop - start)) + }) + .collect()) + } + + /// `ranges` as the ranges of each shard they lie in. + fn per_shard(&self, ranges: &[(u64, u64)]) -> Result>> { + let mut per_shard = vec![Vec::new(); self.parts.len()]; + for &(offset, len) in ranges { + for (index, at, n) in self.pieces(offset, len)? { + per_shard[index].push((at, n)); + } + } + Ok(per_shard) + } + + fn read_with( + &self, + offset: u64, + len: u64, + read: impl Fn(&dyn ByteSource, u64, u64) -> Result>, + ) -> Result> { + // the pieces first: a length past the shards allocates nothing + let pieces = self.pieces(offset, len)?; + let mut out = Vec::with_capacity(usize::try_from(len)?); + for (index, at, n) in pieces { + out.extend(read(self.parts[index].1.as_ref(), at, n)?); + } + Ok(out) + } +} + +impl ByteSource for Shards { + fn read_at(&self, offset: u64, len: u64) -> Result> { + self.read_with(offset, len, |shard, at, n| shard.read_at(at, n)) + } + + fn size(&self) -> u64 { + self.size + } + + fn prefetch(&self, ranges: &[(u64, u64)]) -> Result<()> { + for ((_, shard), ranges) in self.parts.iter().zip(self.per_shard(ranges)?) { + if !ranges.is_empty() { + shard.prefetch(&ranges)?; + } + } + Ok(()) + } + + fn read_once(&self, offset: u64, len: u64) -> Result> { + self.read_with(offset, len, |shard, at, n| shard.read_once(at, n)) + } + + fn missing_bytes(&self, ranges: &[(u64, u64)]) -> Result { + let mut missing = 0u64; + for ((_, shard), ranges) in self.parts.iter().zip(self.per_shard(ranges)?) { + if !ranges.is_empty() { + missing = missing.saturating_add(shard.missing_bytes(&ranges)?); + } + } + Ok(missing) + } +} + +/// The files of the split GGUF whose first shard is `file`, in order, or +/// `None` when `file` is not the first shard of a split. A split of more +/// than [`MAX_SHARDS`] is refused: each shard costs requests and a header. +pub fn shard_files(file: &str) -> Result>> { + let Some((prefix, total)) = first_shard(file) else { + return Ok(None); + }; + let count: usize = total.parse()?; + if count <= 1 { + return Ok(None); + } + if count > MAX_SHARDS { + return refuse(format!( + "{file} names a split of {count} shards, more than {MAX_SHARDS}" + )); + } + Ok(Some( + (1..=count) + .map(|n| format!("{prefix}-{n:05}-of-{total}.gguf")) + .collect(), + )) +} + +/// The prefix and the five-digit shard count of `file`, when it names the +/// first shard of a split. +fn first_shard(file: &str) -> Option<(&str, &str)> { + let stem = file.strip_suffix(".gguf")?; + let (prefix_and_part, total) = stem.rsplit_once("-of-")?; + let (prefix, part) = prefix_and_part.rsplit_once('-')?; + let digits = |s: &str| s.len() == 5 && s.bytes().all(|b| b.is_ascii_digit()); + (digits(part) && digits(total) && part == "00001").then_some((prefix, total)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::weights::limits::CannotAudit; + use crate::weights::test_gguf::Memory; + + fn shards() -> Shards { + Shards::new(vec![ + Box::new(Memory((0u8..10).collect())), + Box::new(Memory((10u8..15).collect())), + Box::new(Memory((15u8..30).collect())), + ]) + .unwrap() + } + + #[test] + fn reads_cross_shard_boundaries() { + let shards = shards(); + assert_eq!(shards.size(), 30); + assert_eq!(shards.read_at(8, 9).unwrap(), (8u8..17).collect::>()); + assert_eq!( + shards.read_at(10, 5).unwrap(), + (10u8..15).collect::>() + ); + assert!(shards.read_at(25, 6).is_err()); + // a length that wraps is past the end, and allocates nothing + assert!(shards.read_at(25, u64::MAX).is_err()); + assert!(shards.read_once(u64::MAX, 2).is_err()); + } + + /// A shard that says it is as large as a file can be. + struct Huge; + + impl ByteSource for Huge { + fn read_at(&self, _offset: u64, _len: u64) -> Result> { + bail!("never read") + } + + fn size(&self) -> u64 { + u64::MAX + } + } + + #[test] + fn shards_larger_than_any_file_are_refused() { + assert!(Shards::new(vec![Box::new(Huge), Box::new(Memory(vec![0]))]).is_err()); + } + + #[test] + fn the_first_shard_names_its_siblings() { + assert_eq!( + shard_files("q/Model-Q4_K_M-00001-of-00003.gguf") + .unwrap() + .unwrap(), + vec![ + "q/Model-Q4_K_M-00001-of-00003.gguf", + "q/Model-Q4_K_M-00002-of-00003.gguf", + "q/Model-Q4_K_M-00003-of-00003.gguf", + ] + ); + let whole = |file: &str| shard_files(file).unwrap().is_none(); + assert!(whole("Model-00002-of-00003.gguf")); + assert!(whole("Model-00001-of-00001.gguf")); + assert!(whole("Model-Q8_0.gguf")); + } + + #[test] + fn a_split_of_too_many_shards_is_refused() { + let most = format!("m-00001-of-{MAX_SHARDS:05}.gguf"); + assert_eq!(shard_files(&most).unwrap().unwrap().len(), MAX_SHARDS); + for file in [ + format!("m-00001-of-{:05}.gguf", MAX_SHARDS + 1), + "m-00001-of-99999.gguf".to_owned(), + ] { + let refused = shard_files(&file).unwrap_err(); + assert!(CannotAudit::caused(&refused), "{refused:#}"); + } + } +} diff --git a/crates/skippy-receipts/src/sparse_copy.rs b/crates/skippy-receipts/src/sparse_copy.rs new file mode 100644 index 00000000..a191c7c5 --- /dev/null +++ b/crates/skippy-receipts/src/sparse_copy.rs @@ -0,0 +1,577 @@ +//! A local copy of a remote GGUF that holds only the bytes an audit read. +//! +//! The copy is a file of the remote file's size. The ranges it holds are +//! fetched on first use and recorded next to it, and the rest stays a hole, +//! so it takes no disk space. The glue check loads a layer from the copy as +//! from a whole GGUF: it never reads the weight matrices, whose opened +//! outputs replace them, and the holes read as zeros. +//! +//! The record names the remote file by its pinned revision and size, and +//! exists from the moment the copy does. A range enters the record only +//! after its bytes are synced to disk, so a crash never leaves a record of +//! bytes that read as zeros. +//! +//! Every opener holds a shared lock on a lock file next to the copy. A copy +//! starts over (its record names another file, or is gone or unreadable, or +//! the data file is gone) only under the exclusive lock, which no opener +//! gets while another has the copy open: bytes another opener is about to +//! record are never truncated. Openers of one copy write the same bytes, +//! and each adds the ranges the others recorded to its own when it saves. +//! +//! The copies under one root stay within a size: [`eviction`] removes the +//! ones used longest ago that no opener holds. + +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions, TryLockError}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::weights::ByteSource; + +pub mod eviction; + +/// Ranges at most this far apart are fetched as one. +const MERGE_GAP: u64 = 64 << 10; +/// The largest range one request fetches. +const MAX_FETCH: u64 = 8 << 20; +/// Requests in flight at once. +const FETCHERS: usize = 16; + +/// Reads byte ranges of the remote file. +pub trait RangeFetch: Send + Sync { + /// The bytes `[offset, offset + len)`, all of them. + fn fetch(&self, offset: u64, len: u64) -> Result>; +} + +/// What the record says the copy is a copy of. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteIdentity { + /// Where the file comes from, pinned: for Hugging Face, + /// `repo@commit/file`. + pub source: String, + pub size: u64, +} + +#[derive(Debug, Serialize, Deserialize)] +struct Record { + identity: RemoteIdentity, + /// Held ranges, `[start, end)`, sorted and apart. + ranges: Vec<(u64, u64)>, +} + +pub struct SparseCopy { + path: PathBuf, + record_path: PathBuf, + identity: RemoteIdentity, + fetcher: Box, + file: File, + /// Held shared while the copy is open. + _lock: File, + /// Held ranges by start. + held: Mutex>, +} + +impl SparseCopy { + /// Opens the copy at `path`, or starts one, of the remote file + /// `identity` names. + pub fn open( + path: &Path, + identity: RemoteIdentity, + fetcher: Box, + ) -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("create {}", parent.display()))?; + } + let record_path = sidecar(path, "ranges"); + let lock_path = sidecar(path, "lock"); + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&lock_path) + .with_context(|| format!("open {}", lock_path.display()))?; + // twice: an eviction may remove the copy between the two locks + let mut opened = None; + for _ in 0..2 { + start_over_unless_open(&lock, &lock_path, path, &record_path, &identity)?; + lock.lock_shared() + .with_context(|| format!("lock {}", lock_path.display()))?; + // read under the shared lock: no opener starts the copy over now + opened = open_held(path, &record_path, &identity); + if opened.is_some() { + break; + } + lock.unlock() + .with_context(|| format!("unlock {}", lock_path.display()))?; + } + let Some((file, held)) = opened else { + bail!( + "the sparse copy {} is open for another file, or is damaged while in use", + path.display() + ); + }; + // the last use, which eviction removes the oldest copies by + let _ = lock.set_modified(std::time::SystemTime::now()); + Ok(Self { + path: path.to_owned(), + record_path, + identity, + fetcher, + file, + _lock: lock, + held: Mutex::new(held), + }) + } + + /// The copy's path, for a loader that reads the GGUF itself. + pub fn path(&self) -> &Path { + &self.path + } + + /// Bytes of the remote file the copy holds. + pub fn held_bytes(&self) -> u64 { + self.held + .lock() + .map(|held| held.iter().map(|(start, end)| end - start).sum()) + .unwrap_or(0) + } + + /// Fetches what the copy lacks of `ranges`, `(offset, len)` each, many + /// requests at once. + pub fn fetch(&self, ranges: &[(u64, u64)]) -> Result<()> { + let plan = { + let held = self.lock()?; + fetch_plan(&held, ranges, self.identity.size)? + }; + if plan.is_empty() { + return Ok(()); + } + let fetchers = FETCHERS.min(plan.len()); + let queue = Mutex::new(plan.into_iter()); + let fetched = Mutex::new(Vec::new()); + let failure = Mutex::new(None); + if fetchers == 1 { + // one request needs no thread + self.fetch_from(&queue, &fetched, &failure); + } else { + std::thread::scope(|scope| { + for _ in 0..fetchers { + scope.spawn(|| self.fetch_from(&queue, &fetched, &failure)); + } + }); + } + // what did fetch stays useful, and is recorded, when a range failed + let saved = self.save(fetched.into_inner().unwrap_or_default()); + match failure.into_inner().ok().flatten() { + Some(error) => Err(error), + None => saved, + } + } + + fn fetch_from( + &self, + queue: &Mutex>, + fetched: &Mutex>, + failure: &Mutex>, + ) { + loop { + let next = queue.lock().ok().and_then(|mut queue| queue.next()); + let Some((start, end)) = next else { + return; + }; + match self.fetch_one(start, end) { + Ok(()) => { + if let Ok(mut fetched) = fetched.lock() { + fetched.push((start, end)); + } + } + Err(error) => { + if let Ok(mut failure) = failure.lock() { + failure.get_or_insert(error); + } + // the other ranges still fetch: they stay useful + } + } + } + } + + fn fetch_one(&self, start: u64, end: u64) -> Result<()> { + let bytes = self + .fetcher + .fetch(start, end - start) + .with_context(|| format!("fetch bytes {start}..{end} of {}", self.identity.source))?; + if bytes.len() as u64 != end - start { + bail!( + "{} sent {} bytes for {start}..{end}", + self.identity.source, + bytes.len() + ); + } + write_at(&self.file, &bytes, start) + } + + /// Records `fetched` ranges as held, once their bytes are on disk. + fn save(&self, fetched: Vec<(u64, u64)>) -> Result<()> { + if fetched.is_empty() { + return Ok(()); + } + // the bytes first: a record of bytes a crash loses would have the + // copy read zeros where the file has weights + self.file + .sync_data() + .with_context(|| format!("sync {}", self.path.display()))?; + let record = { + let mut held = self.lock()?; + for (start, end) in fetched { + insert(&mut held, start, end); + } + // another opener's record names bytes it synced to this file + if let Some(theirs) = read_held(&self.record_path, &self.identity) { + for (start, end) in theirs { + insert(&mut held, start, end); + } + } + Record { + identity: self.identity.clone(), + ranges: held.iter().map(|(&s, &e)| (s, e)).collect(), + } + }; + write_record(&self.record_path, &record) + } + + fn lock(&self) -> Result>> { + self.held + .lock() + .map_err(|_| anyhow::anyhow!("sparse copy lock poisoned")) + } + + /// `[offset, offset + len)` as a range inside the file. + fn range(&self, offset: u64, len: u64) -> Result<(u64, u64)> { + match offset.checked_add(len) { + Some(end) if end <= self.identity.size => Ok((offset, end)), + _ => bail!( + "bytes {offset}+{len} are past the end of the file ({} bytes)", + self.identity.size + ), + } + } +} + +impl ByteSource for SparseCopy { + fn read_at(&self, offset: u64, len: u64) -> Result> { + self.range(offset, len)?; + self.fetch(&[(offset, len)])?; + let mut buf = vec![0u8; usize::try_from(len)?]; + read_at(&self.file, &mut buf, offset)?; + Ok(buf) + } + + fn size(&self) -> u64 { + self.identity.size + } + + fn prefetch(&self, ranges: &[(u64, u64)]) -> Result<()> { + self.fetch(ranges) + } + + fn read_once(&self, offset: u64, len: u64) -> Result> { + let (start, end) = self.range(offset, len)?; + let held = lacking(&*self.lock()?, start, end).is_empty(); + if held { + let mut buf = vec![0u8; usize::try_from(len)?]; + read_at(&self.file, &mut buf, offset)?; + return Ok(buf); + } + let bytes = self.fetcher.fetch(offset, len)?; + if bytes.len() as u64 != len { + bail!( + "{} sent {} bytes, not {len}", + self.identity.source, + bytes.len() + ); + } + Ok(bytes) + } + + /// What fetching `ranges` downloads: the plan [`Self::fetch`] issues, + /// so the small gaps it joins across are charged as well. + fn missing_bytes(&self, ranges: &[(u64, u64)]) -> Result { + let held = self.lock()?; + let plan = fetch_plan(&held, ranges, self.identity.size)?; + Ok(plan.iter().map(|(start, end)| end - start).sum()) + } +} + +/// `path` with `.suffix` added to its file name. +fn sidecar(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.file_name().unwrap_or_default().to_owned(); + name.push("."); + name.push(suffix); + path.with_file_name(name) +} + +/// Opens the data file of a copy of `identity` and the ranges its record +/// says it holds. `None` when the copy is not one of `identity`: no record, +/// a record of another file or one that does not read, or no data file of +/// the file's size. +fn open_held( + path: &Path, + record_path: &Path, + identity: &RemoteIdentity, +) -> Option<(File, BTreeMap)> { + let held = read_held(record_path, identity)?; + let file = OpenOptions::new().read(true).write(true).open(path).ok()?; + (file.metadata().ok()?.len() == identity.size).then_some((file, held)) +} + +/// The ranges the record at `path` says a copy of `identity` holds. +fn read_held(path: &Path, identity: &RemoteIdentity) -> Option> { + let record: Record = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; + if record.identity != *identity { + return None; + } + let mut held = BTreeMap::new(); + for (start, end) in record.ranges { + if start >= end || end > identity.size { + return None; + } + insert(&mut held, start, end); + } + Some(held) +} + +/// Starts the copy at `path` over when it is not one of `identity` and no +/// other opener holds it: under the exclusive lock of `lock`. +fn start_over_unless_open( + lock: &File, + lock_path: &Path, + path: &Path, + record_path: &Path, + identity: &RemoteIdentity, +) -> Result<()> { + match lock.try_lock() { + Ok(()) => { + if open_held(path, record_path, identity).is_none() { + start_over(path, record_path, identity)?; + } + lock.unlock() + .with_context(|| format!("unlock {}", lock_path.display())) + } + Err(TryLockError::WouldBlock) => Ok(()), + Err(TryLockError::Error(error)) => { + Err(error).with_context(|| format!("lock {}", lock_path.display())) + } + } +} + +/// Makes the copy at `path` an empty copy of `identity`. Only under the +/// exclusive lock: no opener has the data file open. +fn start_over(path: &Path, record_path: &Path, identity: &RemoteIdentity) -> Result<()> { + // the record first: none may name bytes that are about to go + match std::fs::remove_file(record_path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| format!("remove {}", record_path.display())); + } + } + let file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(path) + .with_context(|| format!("open {}", path.display()))?; + file.set_len(identity.size) + .with_context(|| format!("size {}", path.display()))?; + let record = Record { + identity: identity.clone(), + ranges: Vec::new(), + }; + write_record(record_path, &record) +} + +/// Writes `record` to `path` through a temporary file of its own, so two +/// writers never share one, and renames it into place. +fn write_record(path: &Path, record: &Record) -> Result<()> { + /// Tells apart the temporary files of one process. + static NEXT: AtomicU64 = AtomicU64::new(0); + let temp = sidecar( + path, + &format!( + "{}.{}.tmp", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ), + ); + // a file a dead process of the same id left: it is no one's now + let _ = std::fs::remove_file(&temp); + let written = (|| -> std::io::Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp)?; + file.write_all(&serde_json::to_vec(record)?)?; + file.sync_all()?; + std::fs::rename(&temp, path) + })(); + if let Err(error) = written { + let _ = std::fs::remove_file(&temp); + return Err(error).with_context(|| format!("write {}", path.display())); + } + // the new name too, where the platform can sync a directory: without + // it a crash may bring the older record back, which names fewer ranges + if let Some(parent) = path.parent() + && let Ok(dir) = File::open(parent) + { + let _ = dir.sync_all(); + } + Ok(()) +} + +/// What `held` lacks of `wanted`, `(offset, len)` each: ranges +/// `[start, end)`, sorted and apart. +fn missing(held: &BTreeMap, wanted: &[(u64, u64)], size: u64) -> Result> { + let mut ranges = Vec::with_capacity(wanted.len()); + for &(offset, len) in wanted { + let end = offset.checked_add(len).filter(|&end| end <= size); + let Some(end) = end else { + bail!("bytes {offset}+{len} are past the end of the file ({size} bytes)"); + }; + if len > 0 { + ranges.push((offset, end)); + } + } + ranges.sort_unstable(); + let mut out: Vec<(u64, u64)> = Vec::new(); + let mut covered = 0; + for (start, end) in ranges { + // what an earlier range covered is not missing twice + let start = start.max(covered); + if start < end { + out.extend(lacking(held, start, end)); + covered = end; + } + } + Ok(out) +} + +/// The ranges to fetch for `wanted`: what `held` lacks, joined across small +/// gaps and split into requests of at most [`MAX_FETCH`]. +fn fetch_plan( + held: &BTreeMap, + wanted: &[(u64, u64)], + size: u64, +) -> Result> { + let mut joined: Vec<(u64, u64)> = Vec::new(); + for (start, end) in missing(held, wanted, size)? { + match joined.last_mut() { + Some(last) if start <= last.1.saturating_add(MERGE_GAP) => last.1 = last.1.max(end), + _ => joined.push((start, end)), + } + } + Ok(joined + .into_iter() + .flat_map(|(start, end)| { + (start..end) + .step_by(MAX_FETCH as usize) + .map(move |s| (s, s.saturating_add(MAX_FETCH).min(end))) + }) + .collect()) +} + +/// The parts of `[start, end)` that `held` lacks. +fn lacking(held: &BTreeMap, start: u64, end: u64) -> Vec<(u64, u64)> { + let mut out = Vec::new(); + if start >= end { + // nothing is wanted, and a range of the map may not end before it starts + return out; + } + let mut at = start; + let before = held.range(..=start).next_back().map(|(&s, &e)| (s, e)); + for (s, e) in before + .into_iter() + .chain(held.range(start + 1..end).map(|(&s, &e)| (s, e))) + { + if e <= at { + continue; + } + if s > at { + out.push((at, s.min(end))); + } + at = at.max(e); + if at >= end { + return out; + } + } + if at < end { + out.push((at, end)); + } + out +} + +/// Adds `[start, end)` to `held`, joining the ranges it meets. +fn insert(held: &mut BTreeMap, mut start: u64, mut end: u64) { + if let Some((&s, &e)) = held.range(..=start).next_back() + && e >= start + { + start = s; + end = end.max(e); + } + let met: Vec = held.range(start..=end).map(|(&s, _)| s).collect(); + for s in met { + if let Some(e) = held.remove(&s) { + end = end.max(e); + } + } + held.insert(start, end); +} + +#[cfg(unix)] +fn write_at(file: &File, bytes: &[u8], offset: u64) -> Result<()> { + use std::os::unix::fs::FileExt; + Ok(file.write_all_at(bytes, offset)?) +} + +#[cfg(unix)] +fn read_at(file: &File, buf: &mut [u8], offset: u64) -> Result<()> { + use std::os::unix::fs::FileExt; + Ok(file.read_exact_at(buf, offset)?) +} + +#[cfg(windows)] +fn write_at(file: &File, mut bytes: &[u8], mut offset: u64) -> Result<()> { + use std::os::windows::fs::FileExt; + while !bytes.is_empty() { + let n = file.seek_write(bytes, offset)?; + if n == 0 { + bail!("the sparse copy took no more bytes at {offset}"); + } + bytes = &bytes[n..]; + offset += n as u64; + } + Ok(()) +} + +#[cfg(windows)] +fn read_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> Result<()> { + use std::os::windows::fs::FileExt; + while !buf.is_empty() { + let n = file.seek_read(buf, offset)?; + if n == 0 { + bail!("read past the end of the sparse copy"); + } + buf = &mut buf[n..]; + offset += n as u64; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/sparse_copy/eviction.rs b/crates/skippy-receipts/src/sparse_copy/eviction.rs new file mode 100644 index 00000000..a8de07ff --- /dev/null +++ b/crates/skippy-receipts/src/sparse_copy/eviction.rs @@ -0,0 +1,248 @@ +//! Keeps the sparse copies under a root within a size: the copies used +//! longest ago go first, and a copy that any opener holds open stays. +//! +//! A copy's size is the bytes its record says it holds, which is what it +//! takes on disk. Its last use is when an opener last opened it, which +//! [`SparseCopy::open`](super::SparseCopy::open) stamps on its lock file. +//! A copy is removed only under the exclusive lock of that file, which no +//! one gets while an opener holds the shared one. The record goes first, +//! then the data, so a crash leaves no record of bytes that are gone. The +//! lock file stays, so an opener waiting on it finds the copy gone and +//! starts it over. + +use std::fs::{OpenOptions, TryLockError}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use anyhow::{Context, Result}; + +use super::{Record, sidecar}; + +/// How deep under the root a copy may be: the repo, the commit and the +/// parts of the file's path. +const MAX_DEPTH: usize = 24; + +/// What an eviction did. +#[derive(Debug, PartialEq, Eq)] +pub struct Evicted { + /// Copies removed. + pub removed: usize, + /// Bytes the copies under the root hold after it. + pub held: u64, +} + +struct Copy { + path: PathBuf, + held: u64, + used: SystemTime, +} + +/// Removes the copies under `root` used longest ago until they hold at most +/// `max_bytes`, except `keep` and the copies that are open. +pub fn evict(root: &Path, max_bytes: u64, keep: &Path) -> Result { + let mut copies = Vec::new(); + collect(root, 0, &mut copies)?; + let mut held = copies + .iter() + .fold(0u64, |sum, c| sum.saturating_add(c.held)); + copies.sort_by_key(|copy| copy.used); + let mut removed = 0; + for copy in copies { + if held <= max_bytes { + break; + } + if copy.path == keep { + continue; + } + if remove_unused(©.path)? { + held = held.saturating_sub(copy.held); + removed += 1; + } + } + Ok(Evicted { removed, held }) +} + +/// The copies under `dir`: each data file with a record next to it. Links +/// are not followed. +fn collect(dir: &Path, depth: usize, copies: &mut Vec) -> Result<()> { + if depth > MAX_DEPTH { + return Ok(()); + } + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).with_context(|| format!("list {}", dir.display())), + }; + for entry in entries { + let entry = entry.with_context(|| format!("list {}", dir.display()))?; + let kind = entry.file_type()?; + let path = entry.path(); + if kind.is_dir() { + collect(&path, depth + 1, copies)?; + continue; + } + let name = entry.file_name(); + let Some(data) = name.to_str().and_then(|n| n.strip_suffix(".ranges")) else { + continue; + }; + if kind.is_file() { + copies.extend(copy_of(&path.with_file_name(data), &path)); + } + } + Ok(()) +} + +/// The copy whose record is at `record`, when the record reads. +fn copy_of(path: &Path, record: &Path) -> Option { + let bytes = std::fs::read(record).ok()?; + let read: Record = serde_json::from_slice(&bytes).ok()?; + let held = read.ranges.iter().fold(0u64, |sum, (start, end)| { + sum.saturating_add(end.saturating_sub(*start)) + }); + let stamp = |file: &Path| std::fs::metadata(file).and_then(|m| m.modified()).ok(); + let used = stamp(&sidecar(path, "lock")) + .or_else(|| stamp(record)) + .unwrap_or(SystemTime::UNIX_EPOCH); + Some(Copy { + path: path.to_owned(), + held, + used, + }) +} + +/// Removes the copy at `path` unless an opener holds it: whether it did. +fn remove_unused(path: &Path) -> Result { + let lock_path = sidecar(path, "lock"); + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&lock_path) + .with_context(|| format!("open {}", lock_path.display()))?; + match lock.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => return Ok(false), + Err(TryLockError::Error(error)) => { + return Err(error).with_context(|| format!("lock {}", lock_path.display())); + } + } + for file in [sidecar(path, "ranges"), path.to_owned()] { + match std::fs::remove_file(&file) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| format!("remove {}", file.display())); + } + } + } + lock.unlock() + .with_context(|| format!("unlock {}", lock_path.display()))?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::super::{RangeFetch, RemoteIdentity, SparseCopy}; + use super::*; + use crate::weights::ByteSource; + + struct Zeros; + + impl RangeFetch for Zeros { + fn fetch(&self, _offset: u64, len: u64) -> Result> { + Ok(vec![7; len as usize]) + } + } + + /// A copy at `root/name` of a file of `size` bytes that holds `held` + /// of them, last used `age` seconds ago. + fn copy(root: &Path, name: &str, size: u64, held: u64, age: u64) -> SparseCopy { + let path = root.join(name).join("model.gguf"); + let identity = RemoteIdentity { + source: name.into(), + size, + }; + let copy = SparseCopy::open(&path, identity, Box::new(Zeros)).unwrap(); + copy.fetch(&[(0, held)]).unwrap(); + let used = SystemTime::now() - Duration::from_secs(age); + let lock = OpenOptions::new() + .write(true) + .open(sidecar(&path, "lock")) + .unwrap(); + lock.set_modified(used).unwrap(); + copy + } + + #[test] + fn the_copies_used_longest_ago_go_first() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for (name, age) in [("old", 300), ("mid", 200), ("new", 100)] { + drop(copy(root, name, 1 << 20, 1000, age)); + } + let evicted = evict(root, 2000, Path::new("")).unwrap(); + assert_eq!( + evicted, + Evicted { + removed: 1, + held: 2000 + } + ); + assert!(!root.join("old/model.gguf").exists()); + assert!(!root.join("old/model.gguf.ranges").exists()); + assert!(root.join("mid/model.gguf").exists()); + // within the cap, nothing goes + assert_eq!(evict(root, 2000, Path::new("")).unwrap().removed, 0); + // a copy removed starts over when it is opened again + let again = copy(root, "old", 1 << 20, 10, 0); + assert_eq!(again.held_bytes(), 10); + } + + #[test] + fn an_open_copy_and_the_one_to_keep_stay() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let open = copy(root, "open", 1 << 20, 1000, 300); + drop(copy(root, "kept", 1 << 20, 1000, 200)); + let evicted = evict(root, 0, &root.join("kept/model.gguf")).unwrap(); + assert_eq!( + evicted, + Evicted { + removed: 0, + held: 2000 + } + ); + assert_eq!(open.read_at(0, 4).unwrap(), vec![7; 4]); + // once closed, it goes + drop(open); + let evicted = evict(root, 0, &root.join("kept/model.gguf")).unwrap(); + assert_eq!( + evicted, + Evicted { + removed: 1, + held: 1000 + } + ); + } + + #[cfg(unix)] + #[test] + fn a_link_out_of_the_root_is_not_followed() { + let dir = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + drop(copy(elsewhere.path(), "theirs", 1 << 20, 1000, 300)); + std::os::unix::fs::symlink(elsewhere.path(), dir.path().join("link")).unwrap(); + let evicted = evict(dir.path(), 0, Path::new("")).unwrap(); + assert_eq!( + evicted, + Evicted { + removed: 0, + held: 0 + } + ); + assert!(elsewhere.path().join("theirs/model.gguf").exists()); + } +} diff --git a/crates/skippy-receipts/src/sparse_copy/tests.rs b/crates/skippy-receipts/src/sparse_copy/tests.rs new file mode 100644 index 00000000..a952b6ca --- /dev/null +++ b/crates/skippy-receipts/src/sparse_copy/tests.rs @@ -0,0 +1,372 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread::ThreadId; + +use super::*; + +/// A remote file in memory that counts the requests and bytes it serves, +/// and notes the thread of each request. +struct Remote { + bytes: Vec, + requests: Arc, + served: Arc, + threads: Arc>>, +} + +impl RangeFetch for Remote { + fn fetch(&self, offset: u64, len: u64) -> Result> { + self.requests.fetch_add(1, Ordering::SeqCst); + self.served.fetch_add(len as usize, Ordering::SeqCst); + self.threads + .lock() + .unwrap() + .push(std::thread::current().id()); + let start = offset as usize; + Ok(self.bytes[start..start + len as usize].to_vec()) + } +} + +/// A remote whose ranges at or past `from` fail. +struct FailsFrom { + remote: Remote, + from: u64, +} + +impl RangeFetch for FailsFrom { + fn fetch(&self, offset: u64, len: u64) -> Result> { + if offset >= self.from { + bail!("the range at {offset} failed"); + } + self.remote.fetch(offset, len) + } +} + +struct Fixture { + _dir: tempfile::TempDir, + path: PathBuf, + bytes: Vec, + requests: Arc, + served: Arc, + threads: Arc>>, +} + +impl Fixture { + fn new(size: usize) -> Self { + let dir = tempfile::tempdir().unwrap(); + Self { + path: dir.path().join("model.gguf"), + _dir: dir, + bytes: (0..size).map(|i| (i % 251) as u8).collect(), + requests: Arc::default(), + served: Arc::default(), + threads: Arc::default(), + } + } + + fn identity(&self, source: &str) -> RemoteIdentity { + RemoteIdentity { + source: source.into(), + size: self.bytes.len() as u64, + } + } + + fn remote(&self) -> Remote { + Remote { + bytes: self.bytes.clone(), + requests: self.requests.clone(), + served: self.served.clone(), + threads: self.threads.clone(), + } + } + + fn open(&self, source: &str) -> SparseCopy { + SparseCopy::open(&self.path, self.identity(source), Box::new(self.remote())).unwrap() + } + + fn record(&self) -> Record { + serde_json::from_slice(&std::fs::read(sidecar(&self.path, "ranges")).unwrap()).unwrap() + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::SeqCst) + } + + fn served(&self) -> usize { + self.served.load(Ordering::SeqCst) + } +} + +#[test] +fn a_copy_fetches_each_byte_once_and_keeps_it() { + let f = Fixture::new(1 << 20); + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.read_at(1000, 10).unwrap(), &f.bytes[1000..1010]); + assert_eq!(copy.read_at(1005, 10).unwrap(), &f.bytes[1005..1015]); + assert_eq!(f.served(), 15); + drop(copy); + // a new process reads what the record says the copy holds + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.read_at(1000, 15).unwrap(), &f.bytes[1000..1015]); + assert_eq!(f.served(), 15); + assert_eq!(copy.held_bytes(), 15); +} + +#[test] +fn a_copy_of_another_file_starts_over() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + copy.read_at(0, 100).unwrap(); + drop(copy); + let copy = f.open("repo@def/model.gguf"); + assert_eq!(copy.held_bytes(), 0); + copy.read_at(0, 100).unwrap(); + assert_eq!(f.served(), 200); +} + +#[test] +fn near_ranges_fetch_as_one_and_far_ones_at_once() { + let f = Fixture::new(64 << 20); + let copy = f.open("repo@abc/model.gguf"); + let ranges = [(0, 10), (100, 10), (40 << 20, 10), (50 << 20, 10)]; + copy.prefetch(&ranges).unwrap(); + assert_eq!(f.requests(), 3); + for (offset, len) in ranges { + let (start, end) = (offset as usize, (offset + len) as usize); + assert_eq!(copy.read_at(offset, len).unwrap(), &f.bytes[start..end]); + } + assert_eq!(f.requests(), 3); +} + +#[test] +fn a_large_range_fetches_in_parts() { + let f = Fixture::new(20 << 20); + let copy = f.open("repo@abc/model.gguf"); + copy.prefetch(&[(0, 20 << 20)]).unwrap(); + assert_eq!(f.requests(), 3); + assert_eq!(copy.read_at(0, 20 << 20).unwrap(), f.bytes); +} + +#[test] +fn a_range_past_the_end_is_refused() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + assert!(copy.read_at(4000, 200).is_err()); + assert_eq!(f.requests(), 0); +} + +#[test] +fn the_held_ranges_join() { + let mut held = BTreeMap::new(); + insert(&mut held, 10, 20); + insert(&mut held, 30, 40); + assert_eq!(lacking(&held, 0, 50), vec![(0, 10), (20, 30), (40, 50)]); + assert_eq!(lacking(&held, 12, 18), vec![]); + assert_eq!(lacking(&held, 15, 35), vec![(20, 30)]); + insert(&mut held, 20, 30); + assert_eq!(held.into_iter().collect::>(), vec![(10, 40)]); +} + +#[test] +fn an_empty_range_is_read_without_a_request() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + copy.read_at(100, 50).unwrap(); + // an empty range inside a held one used to ask the map for a range + // that ends before it starts + assert_eq!(copy.read_once(120, 0).unwrap(), Vec::::new()); + assert_eq!(copy.read_at(120, 0).unwrap(), Vec::::new()); + assert_eq!(copy.missing_bytes(&[(120, 0), (4096, 0)]).unwrap(), 0); + assert_eq!(f.requests(), 1); + let mut held = BTreeMap::new(); + insert(&mut held, 10, 20); + assert_eq!(lacking(&held, 15, 15), vec![]); + assert_eq!(lacking(&held, 15, 14), vec![]); +} + +#[test] +fn offsets_that_wrap_are_past_the_end() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + for (offset, len) in [(u64::MAX, 2), (4000, u64::MAX), (4097, 0), (0, 4097)] { + assert!(copy.read_at(offset, len).is_err(), "{offset}+{len}"); + assert!(copy.read_once(offset, len).is_err(), "{offset}+{len}"); + assert!(copy.prefetch(&[(offset, len)]).is_err(), "{offset}+{len}"); + assert!(copy.missing_bytes(&[(offset, len)]).is_err()); + } + assert_eq!(f.requests(), 0); +} + +#[test] +fn missing_bytes_count_each_byte_once() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + copy.read_at(100, 100).unwrap(); + // 50 are held, and the two ranges share 25 + let ranges = [(150, 100), (225, 100)]; + assert_eq!(copy.missing_bytes(&ranges).unwrap(), 125); + copy.prefetch(&ranges).unwrap(); + assert_eq!(copy.missing_bytes(&ranges).unwrap(), 0); + assert_eq!(f.served(), 225); +} + +#[test] +fn missing_bytes_charge_the_gap_a_fetch_joins() { + let f = Fixture::new(1 << 20); + let copy = f.open("repo@abc/model.gguf"); + // two one-byte ranges a gap apart fetch as one request across the gap + let ranges = [(0, 1), (MERGE_GAP, 1)]; + let charged = copy.missing_bytes(&ranges).unwrap(); + copy.prefetch(&ranges).unwrap(); + assert_eq!(charged, MERGE_GAP + 1); + assert_eq!(f.served() as u64, charged); +} + +#[test] +fn an_opener_never_truncates_a_copy_another_has_open() { + let f = Fixture::new(4096); + let first = f.open("repo@abc/model.gguf"); + first.read_at(1000, 100).unwrap(); + // no record, which once had the next opener empty the file under the + // first, whose ranges then read as zeros + std::fs::remove_file(sidecar(&f.path, "ranges")).unwrap(); + let same = f.identity("repo@abc/model.gguf"); + assert!(SparseCopy::open(&f.path, same, Box::new(f.remote())).is_err()); + // nor does an opener of another file take the copy over + let other = f.identity("repo@def/model.gguf"); + let refused = SparseCopy::open(&f.path, other, Box::new(f.remote())) + .err() + .unwrap() + .to_string(); + assert!(refused.contains("open for another file"), "{refused}"); + assert_eq!(first.read_at(1000, 100).unwrap(), &f.bytes[1000..1100]); + assert_eq!(f.served(), 100); + drop(first); + // with no opener left, the copy starts over + let again = f.open("repo@abc/model.gguf"); + assert_eq!(again.held_bytes(), 0); + assert_eq!(again.read_at(1000, 100).unwrap(), &f.bytes[1000..1100]); +} + +#[test] +fn a_record_without_its_data_file_is_discarded() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + copy.read_at(0, 100).unwrap(); + drop(copy); + std::fs::remove_file(&f.path).unwrap(); + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.held_bytes(), 0); + assert!(f.record().ranges.is_empty()); + assert_eq!(copy.read_at(0, 100).unwrap(), &f.bytes[..100]); + assert_eq!(f.served(), 200); +} + +#[test] +fn a_record_that_does_not_read_starts_the_copy_over() { + let f = Fixture::new(4096); + let identity = serde_json::to_value(f.identity("repo@abc/model.gguf")).unwrap(); + for ranges in [ + serde_json::json!([[0, 5000]]), + serde_json::json!([[10, 10]]), + serde_json::json!([[20, 10]]), + serde_json::json!("all of it"), + ] { + f.open("repo@abc/model.gguf").read_at(0, 10).unwrap(); + let record = serde_json::json!({"identity": identity, "ranges": ranges}); + std::fs::write(sidecar(&f.path, "ranges"), record.to_string()).unwrap(); + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.held_bytes(), 0, "{ranges}"); + } + std::fs::write(sidecar(&f.path, "ranges"), b"not json").unwrap(); + assert_eq!(f.open("repo@abc/model.gguf").held_bytes(), 0); + // a copy shorter than the file is not a copy of it + f.open("repo@abc/model.gguf").read_at(0, 10).unwrap(); + std::fs::write(&f.path, b"short").unwrap(); + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.held_bytes(), 0); + assert_eq!(copy.read_at(0, 10).unwrap(), &f.bytes[..10]); +} + +#[test] +fn a_copy_has_a_record_from_the_start() { + let f = Fixture::new(4096); + let copy = f.open("repo@abc/model.gguf"); + let record = f.record(); + assert_eq!(record.identity, f.identity("repo@abc/model.gguf")); + assert!(record.ranges.is_empty()); + copy.read_at(8, 8).unwrap(); + assert_eq!(f.record().ranges, vec![(8, 16)]); +} + +#[test] +fn openers_of_one_copy_keep_each_others_ranges() { + let f = Fixture::new(1 << 20); + let first = f.open("repo@abc/model.gguf"); + let second = f.open("repo@abc/model.gguf"); + first.read_at(0, 100).unwrap(); + second.read_at(500_000, 100).unwrap(); + // the first learns of the second's range when it next records one + first.read_at(200, 100).unwrap(); + assert_eq!(first.held_bytes(), 300); + assert_eq!( + first.read_at(500_000, 100).unwrap(), + &f.bytes[500_000..500_100] + ); + drop((first, second)); + let copy = f.open("repo@abc/model.gguf"); + assert_eq!(copy.held_bytes(), 300); + assert_eq!(f.served(), 300); +} + +#[test] +fn two_copies_in_one_process_record_at_once() { + let f = Fixture::new(1 << 20); + let copies = [f.open("repo@abc/model.gguf"), f.open("repo@abc/model.gguf")]; + std::thread::scope(|scope| { + for (n, copy) in copies.iter().enumerate() { + scope.spawn(move || { + for i in 0..50u64 { + // far apart, so every read records a range of its own + copy.read_at((2 * i + n as u64) * 2048, 8).unwrap(); + } + }); + } + }); + drop(copies); + assert_eq!(f.served(), 100 * 8); + let left: Vec<_> = std::fs::read_dir(f.path.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .filter(|name| name.ends_with(".tmp")) + .collect(); + assert!(left.is_empty(), "{left:?}"); +} + +#[test] +fn one_range_is_fetched_on_the_calling_thread() { + let f = Fixture::new(64 << 20); + let copy = f.open("repo@abc/model.gguf"); + copy.read_at(0, 100).unwrap(); + let here = std::thread::current().id(); + assert_eq!(*f.threads.lock().unwrap(), vec![here]); + f.threads.lock().unwrap().clear(); + copy.prefetch(&[(1 << 20, 10), (40 << 20, 10)]).unwrap(); + let threads = f.threads.lock().unwrap().clone(); + assert_eq!(threads.len(), 2); + assert!(!threads.contains(&here)); +} + +#[test] +fn a_failed_range_keeps_the_ranges_that_fetched() { + let f = Fixture::new(64 << 20); + let remote = FailsFrom { + remote: f.remote(), + from: 30 << 20, + }; + let identity = f.identity("repo@abc/model.gguf"); + let copy = SparseCopy::open(&f.path, identity, Box::new(remote)).unwrap(); + assert!(copy.prefetch(&[(0, 10), (40 << 20, 10)]).is_err()); + assert_eq!(copy.held_bytes(), 10); + drop(copy); + assert_eq!(f.open("repo@abc/model.gguf").held_bytes(), 10); +} diff --git a/crates/skippy-receipts/src/toy_turn.rs b/crates/skippy-receipts/src/toy_turn.rs new file mode 100644 index 00000000..66956489 --- /dev/null +++ b/crates/skippy-receipts/src/toy_turn.rs @@ -0,0 +1,995 @@ +//! A toy model and an honest turn of it, for tests of the client's checks. +//! +//! The model has [`LAYERS`] layers of [`HIDDEN`] values, one stage per +//! layer, and a vocabulary of [`VOCABULARY`] tokens. Each layer has what +//! the checks tell apart: +//! +//! ```text +//! matmul 0 (blk.L.a.weight): input = 2 · residual +//! matmul 1 (blk.L.router.weight): input = residual, a router +//! selection 0: the experts, best score first +//! matmul 2 (blk.L.exps.weight): input = residual, for the two best experts +//! mixing input 0: residual +//! stored row 0: residual, as f16 +//! mixing output 0: a value per position +//! residual out = residual + (matmul 0 + both expert outputs) / 8 + mixing output 0 +//! ``` +//! +//! [`weights`] is its GGUF, [`ToyModel`] the evaluator an auditor computes +//! a layer with, and [`Turn`] a turn a node served honestly: its receipt +//! and the opening of any challenge. A test changes one thing in an opening +//! and expects the check that owns it to fail. + +use anyhow::{Context, Result, bail}; +use ed25519_dalek::SigningKey; + +use crate::attention::opening::{BlockChallenge, stored_digests}; +use crate::cache_types; +use crate::commitment::{ + Hash, MerkleTree, MixingValue, cell_digest, encode_path, mixing_leaf, position_digest, + prefix_leaf, prefix_tokens_digest, residual_leaf, slots_per_position, stored_leaf, +}; +use crate::glue::{GlueEvaluator, GlueOutput, GlueRequest, GlueTensor, GlueValues, StoredRowError}; +use crate::head::OutputHead; +use crate::layer_tensors::{FLAG_ROUTER, GGML_F32, TensorKind, f32_bytes}; +use crate::turn::{self, BindingRequest}; +use crate::weights::{ByteSource, WeightFile}; +use crate::wire::{ + AnchorOpening, BoundaryLeaf, Challenge, HeadOpening, LayerOpening, LeafOpening, MatrixOpening, + MixingKind, Opening, Pick, PrefixCommitment, PrefixOpening, RECEIPT_VERSION, Receipt, + SelectionOpening, StageCommitment, StageOpening, TensorOpening, encode_f32, +}; + +pub(crate) const HIDDEN: usize = 4; +pub(crate) const VOCABULARY: usize = 8; +pub(crate) const EXPERTS: usize = 3; +pub const LAYERS: u32 = 2; +/// Experts each position is routed to. +pub(crate) const ROUTED: usize = 2; +/// The runtime the toy node says it ran, and [`ToyModel`] runs. +pub const RUNTIME: &str = "toy-runtime 1"; +/// ggml type of the stored rows: f16. +pub(crate) const CACHE_TYPE: i32 = 1; +const RECEIPT_ID: &str = "toy-turn"; + +/// A GGUF held in memory. +pub struct Memory(pub Vec); + +impl ByteSource for Memory { + fn read_at(&self, offset: u64, len: u64) -> Result> { + let start = usize::try_from(offset)?; + let end = start.saturating_add(usize::try_from(len)?); + self.0 + .get(start..end) + .map(<[u8]>::to_vec) + .context("read past the end") + } + + fn size(&self) -> u64 { + self.0.len() as u64 + } +} + +/// A weight value: a small multiple of 1/8, different for every tensor. +fn weight_value(tensor: usize, i: usize) -> f32 { + ((tensor * 31 + i * 17 + 5) % 23) as f32 * 0.125 - 1.25 +} + +/// The model's tensors: name, dimensions and f32 values. +fn tensors() -> Vec<(String, Vec, Vec)> { + let (h, e, v) = (HIDDEN as u64, EXPERTS as u64, VOCABULARY as u64); + let mut shapes = Vec::new(); + for layer in 0..LAYERS { + shapes.push((format!("blk.{layer}.a.weight"), vec![h, h])); + shapes.push((format!("blk.{layer}.router.weight"), vec![h, e])); + shapes.push((format!("blk.{layer}.exps.weight"), vec![h, h, e])); + } + shapes.push(("output_norm.weight".to_owned(), vec![h])); + shapes.push(("token_embd.weight".to_owned(), vec![h, v])); + shapes + .into_iter() + .enumerate() + .map(|(tensor, (name, dims))| { + let count = dims.iter().product::() as usize; + let values = (0..count).map(|i| weight_value(tensor, i)).collect(); + (name, dims, values) + }) + .collect() +} + +fn gguf_string(out: &mut Vec, text: &str) { + out.extend((text.len() as u64).to_le_bytes()); + out.extend(text.as_bytes()); +} + +/// The model's GGUF: its metadata and f32 tensors. +pub(crate) fn gguf_bytes() -> Vec { + let tensors = tensors(); + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend((tensors.len() as u64).to_le_bytes()); + out.extend(4u64.to_le_bytes()); + gguf_string(&mut out, "general.architecture"); + out.extend(8u32.to_le_bytes()); + gguf_string(&mut out, "toy"); + for (key, value) in [ + ("toy.embedding_length", HIDDEN as u64), + ("toy.block_count", u64::from(LAYERS)), + ] { + gguf_string(&mut out, key); + out.extend(10u32.to_le_bytes()); + out.extend(value.to_le_bytes()); + } + gguf_string(&mut out, "toy.attention.layer_norm_rms_epsilon"); + out.extend(12u32.to_le_bytes()); + out.extend(1e-6f64.to_le_bytes()); + let mut offset = 0u64; + for (name, dims, values) in &tensors { + gguf_string(&mut out, name); + out.extend((dims.len() as u32).to_le_bytes()); + for d in dims { + out.extend(d.to_le_bytes()); + } + out.extend(0u32.to_le_bytes()); + out.extend(offset.to_le_bytes()); + offset += (values.len() as u64 * 4).div_ceil(32) * 32; + } + out.resize(out.len().div_ceil(32) * 32, 0); + for (_, _, values) in &tensors { + out.extend(f32_bytes(values)); + out.resize(out.len().div_ceil(32) * 32, 0); + } + out +} + +/// The model's GGUF, opened. +pub fn weights() -> WeightFile { + WeightFile::open(Box::new(Memory(gguf_bytes()))).expect("the toy GGUF") +} + +/// A GGUF whose header reads and whose weights do not, as a sparse copy +/// whose remote is out of reach. +struct HeaderOnly { + bytes: Vec, + header: u64, +} + +impl ByteSource for HeaderOnly { + // the header is read from the file's start; a weight starts after it + fn read_at(&self, offset: u64, len: u64) -> Result> { + if offset >= self.header { + bail!("the claimed GGUF is out of reach"); + } + Memory(self.bytes.clone()).read_at(offset, len) + } + + fn size(&self) -> u64 { + self.bytes.len() as u64 + } + + fn prefetch(&self, ranges: &[(u64, u64)]) -> Result<()> { + if ranges.iter().any(|(offset, _)| *offset >= self.header) { + bail!("the claimed GGUF is out of reach"); + } + Ok(()) + } +} + +/// The model's GGUF with its header at hand and its weights out of reach: +/// every weight read fails, which is the client's trouble and not a node's. +pub fn weights_out_of_reach() -> WeightFile { + let header = weights().header_bytes; + let source = HeaderOnly { + bytes: gguf_bytes(), + header, + }; + WeightFile::open(Box::new(source)).expect("the toy GGUF's header") +} + +/// The residual entering layer 0 for a token at a position. +pub fn entry(token: i32, position: u32) -> Vec { + vec![token as f32 * 0.25, position as f32 * 0.5, 1.0, -0.5] +} + +/// The token-mixing output of a layer at a position: what attention would +/// give. +fn mixing_output(layer: u32, position: u32) -> Vec { + vec![ + 0.125 * (position + 1) as f32, + -0.25, + 0.5 * layer as f32, + 0.0625, + ] +} + +/// A tensor's values, by name. +fn tensor_values(name: &str) -> Vec { + tensors() + .into_iter() + .find(|(tensor, _, _)| tensor == name) + .map(|(_, _, values)| values) + .expect("a tensor of the toy model") +} + +/// `rows` rows of `HIDDEN` weights, from `first`, times `x`. +fn matmul(weight: &[f32], first: usize, rows: usize, x: &[f32]) -> Vec { + (first..first + rows) + .map(|row| { + let w = &weight[row * HIDDEN..(row + 1) * HIDDEN]; + w.iter() + .zip(x) + .map(|(&w, &x)| f64::from(w) * f64::from(x)) + .sum::() as f32 + }) + .collect() +} + +/// The experts, best score first. +fn ranked(scores: &[f32]) -> Vec { + let mut ids: Vec = (0..scores.len() as i32).collect(); + ids.sort_by(|&a, &b| scores[b as usize].total_cmp(&scores[a as usize])); + ids +} + +/// The residual leaving a layer, from what entered it and what its matmuls +/// and token mixing gave. +fn residual_out(residual: &[f32], a_out: &[f32], experts_out: &[f32], mixing: &[f32]) -> Vec { + (0..HIDDEN) + .map(|i| { + let experts: f32 = experts_out.chunks(HIDDEN).map(|chunk| chunk[i]).sum(); + residual[i] + (a_out[i] + experts) * 0.125 + mixing[i] + }) + .collect() +} + +/// One position of one layer, as an honest node computes it. +#[derive(Clone, Debug)] +struct Computed { + residual_in: Vec, + a_out: Vec, + router_out: Vec, + selection: Vec, + experts_out: Vec, + mixing_out: Vec, + residual_out: Vec, +} + +impl Computed { + fn new(layer: u32, position: u32, residual_in: Vec) -> Self { + let doubled: Vec = residual_in.iter().map(|v| v * 2.0).collect(); + let a_out = matmul( + &tensor_values(&format!("blk.{layer}.a.weight")), + 0, + HIDDEN, + &doubled, + ); + let router = tensor_values(&format!("blk.{layer}.router.weight")); + let router_out = matmul(&router, 0, EXPERTS, &residual_in); + let selection = ranked(&router_out); + let experts = tensor_values(&format!("blk.{layer}.exps.weight")); + let experts_out: Vec = selection[..ROUTED] + .iter() + .flat_map(|&e| matmul(&experts, e as usize * HIDDEN, HIDDEN, &residual_in)) + .collect(); + let mixing_out = mixing_output(layer, position); + let residual_out = residual_out(&residual_in, &a_out, &experts_out, &mixing_out); + Self { + residual_in, + a_out, + router_out, + selection, + experts_out, + mixing_out, + residual_out, + } + } + + fn stored(&self) -> Vec { + self.residual_in + .iter() + .flat_map(|&v| half::f16::from_f32(v).to_le_bytes()) + .collect() + } + + fn mixing(&self) -> Vec { + let f32_value = |kind, values: &[f32]| { + TensorOpening::new(kind, 0, Some((GGML_F32, &f32_bytes(values)))) + }; + vec![ + f32_value(MixingKind::Input, &self.residual_in), + TensorOpening::new(MixingKind::Stored, 0, Some((CACHE_TYPE, &self.stored()))), + f32_value(MixingKind::Output, &self.mixing_out), + ] + } + + fn matrices(&self, layer: u32) -> Vec { + let doubled: Vec = self.residual_in.iter().map(|v| v * 2.0).collect(); + let matrix = + |index, name: &str, router, experts, input: &[f32], output: &[f32]| MatrixOpening { + index, + weight: format!("blk.{layer}.{name}.weight"), + router, + experts, + input: encode_f32(input), + output: encode_f32(output), + }; + vec![ + matrix(0, "a", false, None, &doubled, &self.a_out), + matrix(1, "router", true, None, &self.residual_in, &self.router_out), + matrix( + 2, + "exps", + false, + Some(self.selection[..ROUTED].to_vec()), + &self.residual_in, + &self.experts_out, + ), + ] + } +} + +/// The auditor's evaluation of the toy model: every layer is at hand, and +/// a layer is computed on the opened values as the native evaluator +/// computes one, taking an unopened value as zeros. +pub struct ToyModel; + +/// Column `col` of an opened f32 value of `len` values, or zeros. +fn opened_f32( + request: &GlueRequest, + kind: TensorKind, + index: u32, + col: usize, + len: usize, +) -> Vec { + let input = request + .inputs + .iter() + .find(|i| i.kind == kind && i.index == index); + match input.map(|input| (&input.values, input.len)) { + Some((GlueValues::F32(values), width)) if width == len => values + .get(col * len..(col + 1) * len) + .map_or_else(|| vec![0.0; len], <[f32]>::to_vec), + _ => vec![0.0; len], + } +} + +/// Column `col` of the opened selection, or no ids. +fn opened_selection(request: &GlueRequest, col: usize) -> Vec { + let input = request + .inputs + .iter() + .find(|i| i.kind == TensorKind::Selection && i.index == 0); + match input.map(|input| (&input.values, input.len)) { + Some((GlueValues::I32(ids), len)) => ids + .get(col * len..(col + 1) * len) + .map_or_else(Vec::new, <[i32]>::to_vec), + _ => Vec::new(), + } +} + +/// Refuses a value the toy layer does not take, as the native evaluator +/// refuses one, in its words: a value no node takes, one of another +/// length, a selected id out of range, a mixing output left out. +fn refuse_values(request: &GlueRequest) -> Result<()> { + let takes = |kind, index| match (kind, index) { + (TensorKind::MatmulOutput, 0) | (TensorKind::MixingOutput, 0) => Some(HIDDEN), + (TensorKind::MatmulOutput, 1) => Some(EXPERTS), + (TensorKind::MatmulOutput, 2) => Some(ROUTED * HIDDEN), + // the full order of the experts by score + (TensorKind::Selection, 0) => Some(EXPERTS), + _ => None, + }; + for input in &request.inputs { + let Some(len) = takes(input.kind, input.index) else { + bail!( + "an opened value (kind {}, index {}) matches nothing in the layer", + input.kind.code(), + input.index + ); + }; + if input.len != len { + bail!( + "the opened value for {} {} has {} elements per column, the graph {len}", + input.kind.name(), + input.index, + input.len + ); + } + if let GlueValues::I32(ids) = &input.values + && ids + .iter() + .any(|&id| !usize::try_from(id).is_ok_and(|id| id < EXPERTS)) + { + bail!("the opened selection for scores holds an id outside the {EXPERTS} rows"); + } + } + if !request + .inputs + .iter() + .any(|input| input.kind == TensorKind::MixingOutput) + { + bail!("no opened value for attn_out"); + } + Ok(()) +} + +impl GlueEvaluator for ToyModel { + fn evaluate(&self, request: &GlueRequest) -> Result { + refuse_values(request)?; + let layer = request.layer; + let columns = request.positions.len(); + if request.residual.len() != columns * HIDDEN { + bail!("the residual is not {HIDDEN} values per position"); + } + let (mut doubled, mut scores, mut routed, mut out) = (vec![], vec![], vec![], vec![]); + for col in 0..columns { + let residual = &request.residual[col * HIDDEN..(col + 1) * HIDDEN]; + doubled.extend(residual.iter().map(|v| v * 2.0)); + scores.extend(opened_f32( + request, + TensorKind::MatmulOutput, + 1, + col, + EXPERTS, + )); + let mut ids = opened_selection(request, col); + ids.resize(ROUTED, 0); + routed.extend(ids); + let a_out = opened_f32(request, TensorKind::MatmulOutput, 0, col, HIDDEN); + let experts_out = + opened_f32(request, TensorKind::MatmulOutput, 2, col, ROUTED * HIDDEN); + let mixing = opened_f32(request, TensorKind::MixingOutput, 0, col, HIDDEN); + out.extend(residual_out(residual, &a_out, &experts_out, &mixing)); + } + let residual = request.residual.clone(); + let tensor = |kind, index, flags, name: String, len, values| GlueTensor { + layer: if kind == TensorKind::Residual { + layer + 1 + } else { + layer + }, + kind, + index, + flags, + name, + len, + values, + }; + let weight = |name: &str| format!("blk.{layer}.{name}.weight"); + let f32s = GlueValues::F32; + Ok(GlueOutput { + tensors: vec![ + tensor( + TensorKind::MatmulInput, + 0, + 0, + weight("a"), + HIDDEN, + f32s(doubled), + ), + tensor( + TensorKind::MatmulInput, + 1, + FLAG_ROUTER, + weight("router"), + HIDDEN, + f32s(residual.clone()), + ), + tensor( + TensorKind::MatmulInput, + 2, + 0, + weight("exps"), + HIDDEN, + f32s(residual.clone()), + ), + tensor( + TensorKind::ExpertIds, + 2, + 0, + weight("exps"), + ROUTED, + GlueValues::I32(routed), + ), + tensor( + TensorKind::MixingInput, + 0, + 0, + "q".to_owned(), + HIDDEN, + f32s(residual.clone()), + ), + tensor( + TensorKind::MixingStored, + 0, + 0, + "k".to_owned(), + HIDDEN, + f32s(residual), + ), + tensor( + TensorKind::SelectionScores, + 0, + 0, + "scores".to_owned(), + EXPERTS, + f32s(scores), + ), + tensor( + TensorKind::Residual, + 0, + 0, + "l_out".to_owned(), + HIDDEN, + f32s(out), + ), + ], + unchecked_weights: Vec::new(), + attention: Vec::new(), + }) + } + + fn evaluate_region(&self, _: &GlueRequest) -> Result { + bail!("the toy model keeps no recurrent state") + } + + fn entry(&self, tokens: &[i32], positions: &[i32]) -> Result> { + Ok(tokens + .iter() + .zip(positions) + .flat_map(|(&token, &position)| entry(token, position as u32)) + .collect()) + } + + fn stored_row_error( + &self, + ggml_type: i32, + stored: &[u8], + computed: &[f32], + ) -> Result { + let stored = cache_types::decode_row(ggml_type, stored)?; + if stored.len() != computed.len() { + bail!("a stored row of another length than the computed one"); + } + let l2 = |values: &mut dyn Iterator| values.map(|v| v * v).sum::().sqrt(); + let rounded = |v: f32| f64::from(half::f16::from_f32(v).to_f32()); + Ok(StoredRowError { + stored: l2(&mut stored.iter().zip(computed).map(|(s, &c)| s - f64::from(c))), + rounding: l2(&mut computed.iter().map(|&c| rounded(c) - f64::from(c))), + norm: l2(&mut computed.iter().map(|&c| f64::from(c))), + }) + } +} + +/// The best token for the residual leaving the final layer. +fn greedy_token(weights: &WeightFile, head: &OutputHead, residual: &[f32]) -> (i32, Vec) { + let logits = head + .logits(weights, &[residual.to_vec()]) + .expect("the toy head") + .remove(0); + let best = logits + .iter() + .enumerate() + .max_by(|a, b| a.1.total_cmp(b.1)) + .map_or(0, |(token, _)| token as i32); + (best, logits.iter().map(|&l| l as f32).collect()) +} + +/// A turn of the toy model an honest node served. +pub struct Turn { + pub receipt: Receipt, + /// By layer, then by position of the turn. + computed: Vec>, + /// The logits at every position of the turn. + logits: Vec>, + trees: Vec, + /// The cached prefix the turn continued, which an earlier request + /// computed. + prefix: Prefix, + node: SigningKey, +} + +/// The cached prefix of a toy turn: what an honest node computed at every +/// position below the turn, and what each stage commits of it. The cell of +/// a position has the position's index. +struct Prefix { + tokens: Vec, + /// By layer, then by position. + computed: Vec>, + /// By stage, then by position: the leaves the stage committed. + leaves: Vec>, + /// By stage: the tree over the prefix leaves. Empty for a turn from + /// position 0. + trees: Vec, +} + +impl Prefix { + /// The prefix of `length` positions: token `1 + p % 3` at position `p`. + fn new(length: u32) -> Self { + let tokens: Vec = (0..length as i32).map(|p| 1 + p % 3).collect(); + let mut computed: Vec> = vec![Vec::new(); LAYERS as usize]; + for position in 0..length { + let mut residual = entry(tokens[position as usize], position); + for layer in 0..LAYERS { + let values = Computed::new(layer, position, residual); + residual = values.residual_out.clone(); + computed[layer as usize].push(values); + } + } + let leaves: Vec> = (0..LAYERS) + .map(|layer| { + (0..length) + .map(|p| { + let token = (layer == 0).then(|| tokens[p as usize]); + position_leaves(layer, p, token, &computed[layer as usize][p as usize]) + }) + .collect() + }) + .collect(); + let trees = (0..LAYERS) + .filter(|_| length > 0) + .map(|layer| { + let leaves = (0..length) + .map(|p| { + let values = &computed[layer as usize][p as usize]; + prefix_leaf( + p as i32, + p, + &cell_digest(vec![stored_leaf_of(layer, p, values)]).expect("a cell"), + &position_digest(&leaves[layer as usize][p as usize]), + ) + }) + .collect(); + MerkleTree::new(leaves).expect("a prefix has positions") + }) + .collect(); + Self { + tokens, + computed, + leaves, + trees, + } + } + + fn len(&self) -> u32 { + self.tokens.len() as u32 + } + + /// What stage `stage` commits of the prefix. + fn commitment(&self, stage: u32) -> Option { + let tree = self.trees.get(stage as usize)?; + Some(PrefixCommitment { + root: hex::encode(tree.root()), + positions: self.len(), + tokens: (stage == 0).then(|| hex::encode(prefix_tokens_digest(&self.tokens))), + }) + } + + /// What stage `stage` opens of the prefix at `position`. + fn open(&self, stage: u32, position: u32) -> PrefixOpening { + let values = &self.computed[stage as usize][position as usize]; + let tree = &self.trees[stage as usize]; + PrefixOpening { + position, + cell: position, + leaves: self.leaves[stage as usize][position as usize] + .iter() + .map(hex::encode) + .collect(), + stored: vec![hex::encode(stored_leaf_of(stage, position, values))], + path: encode_path(&tree.path(u64::from(position)).expect("a path")), + } + } +} + +/// The leaf of the row `layer` stored at `position`. +fn stored_leaf_of(layer: u32, position: u32, values: &Computed) -> Hash { + let stored: Vec = values + .mixing() + .into_iter() + .filter(|value| value.kind == MixingKind::Stored) + .collect(); + stored_leaf( + position, + layer, + &stored_digests(&stored).expect("stored rows"), + ) +} + +impl Turn { + /// A turn from position 0, not bound to a client. + pub fn new() -> Self { + Self::starting_at(0) + } + + /// A turn that continues a cached prefix of `start` positions: three + /// prompt positions, then two sampled tokens and a final one. + pub fn starting_at(start: u32) -> Self { + let weights = weights(); + let head = OutputHead::from_weights(&weights).expect("the toy head"); + let prompt = 3u32; + let end = start + prompt + 2; + let mut tokens: Vec = (0..prompt as i32).map(|i| 1 + i).collect(); + let mut computed: Vec> = vec![Vec::new(); LAYERS as usize]; + let mut logits = Vec::new(); + let mut final_token = None; + for position in start..end { + let token = tokens[(position - start) as usize]; + let mut residual = entry(token, position); + for layer in 0..LAYERS { + let values = Computed::new(layer, position, residual); + residual = values.residual_out.clone(); + computed[layer as usize].push(values); + } + let (best, at_position) = greedy_token(&weights, &head, &residual); + logits.push(at_position); + // the turn samples from the last prompt position on + if position + 1 == end { + final_token = Some(best); + } else if position + 1 >= start + prompt { + tokens.push(best); + } + } + let trees: Vec = (0..LAYERS) + .map(|layer| stage_tree(layer, start, &tokens, &computed[layer as usize])) + .collect(); + let prefix = Prefix::new(start); + let stages = trees + .iter() + .enumerate() + .map(|(i, tree)| StageCommitment { + stage_index: i as u32, + layer_start: i as u32, + layer_end: i as u32 + 1, + root: hex::encode(tree.root()), + leaf_count: tree.leaf_count(), + backend: "CPU".to_owned(), + cache_types: vec!["f16".to_owned()], + prefix: prefix.commitment(i as u32), + ubatches: Vec::new(), + recurrent_state: None, + }) + .collect(); + Self { + receipt: Receipt { + version: RECEIPT_VERSION, + receipt_id: RECEIPT_ID.to_owned(), + model: "toy/model@main/toy.gguf".to_owned(), + position_start: start, + position_end: end, + tokens, + generation_start: start + prompt, + final_token, + stages, + binding: None, + }, + computed, + logits, + trees, + prefix, + node: SigningKey::from_bytes(&[5; 32]), + } + } + + /// Binds the receipt to `client_key` with the sampler statement + /// `sampler`, signed by the toy node. + #[must_use] + pub fn bound(mut self, client_key: [u8; 32], sampler: &str) -> Self { + let request = BindingRequest { + client_key, + parent: None, + runtime: RUNTIME.to_owned(), + sampler: sampler.to_owned(), + }; + turn::bind(&mut self.receipt, &request, &self.node); + self + } + + /// A challenge of `picks`, each a layer and its positions, and `head` + /// positions. + pub fn challenge(&self, picks: &[(u32, &[u32])], head: &[u32]) -> Challenge { + Challenge { + receipt_id: self.receipt.receipt_id.clone(), + picks: picks + .iter() + .map(|(layer, positions)| Pick { + layer: *layer, + positions: positions.to_vec(), + }) + .collect(), + proof: None, + head: head.to_vec(), + attention: Vec::new(), + } + } + + fn at(&self, layer: u32, position: u32) -> &Computed { + match position.checked_sub(self.receipt.position_start) { + Some(index) => &self.computed[layer as usize][index as usize], + None => &self.prefix.computed[layer as usize][position as usize], + } + } + + /// The token at `position` of the turn or of its prefix. + fn token(&self, position: u32) -> i32 { + self.receipt + .token_at(position) + .unwrap_or_else(|| self.prefix.tokens[position as usize]) + } + + /// The path of a leaf of stage `stage` at `position`. A leaf of a + /// prefix position is in no tree, and has none. + fn path(&self, stage: u32, position: u32, slot: u64) -> (Hash, Vec) { + if position < self.receipt.position_start { + let leaves = &self.prefix.leaves[stage as usize][position as usize]; + return (leaves[slot as usize], Vec::new()); + } + let tree = &self.trees[stage as usize]; + let index = u64::from(position - self.receipt.position_start) * SLOTS + slot; + let leaf = tree.leaf(index).expect("a leaf of the turn"); + (leaf, encode_path(&tree.path(index).expect("a path"))) + } + + fn leaf(&self, layer: u32, position: u32) -> LeafOpening { + let values = self.at(layer, position); + LeafOpening { + position, + residual_in: encode_f32(&values.residual_in), + residual_out: Some(encode_f32(&values.residual_out)), + residual_in_path: self.path(layer, position, 0).1, + mixing_path: self.path(layer, position, 1).1, + residual_out_path: self.path(layer, position, 2).1, + mixing: values.mixing(), + matrices: values.matrices(layer), + selections: vec![SelectionOpening { + index: 0, + ids: values.selection.clone(), + }], + } + } + + fn boundary(&self, stage: u32, position: u32, slot: u64) -> BoundaryLeaf { + let (leaf, path) = self.path(stage, position, slot); + BoundaryLeaf { + position, + leaf: hex::encode(leaf), + path, + } + } + + /// What an honest node opens for `challenge`. + pub fn open(&self, challenge: &Challenge) -> Opening { + let positions = challenge.positions(); + let stages = (0..LAYERS) + .map(|stage| { + let picks = challenge.picks.iter().filter(|p| p.layer == stage); + let layers = picks + .map(|pick| LayerOpening { + layer: pick.layer, + leaves: pick + .positions + .iter() + .map(|&p| self.leaf(pick.layer, p)) + .collect(), + }) + .collect(); + let boundaries = |slot: u64| -> Vec { + positions + .iter() + .map(|&p| self.boundary(stage, p, slot)) + .collect() + }; + StageOpening { + stage_index: stage, + layers, + anchors: positions + .iter() + .filter(|_| stage == 0) + .map(|&p| self.anchor(p)) + .collect(), + entry: if stage > 0 { boundaries(0) } else { Vec::new() }, + exit: boundaries(2), + head: challenge + .head + .iter() + .filter(|_| stage + 1 == LAYERS) + .map(|&p| self.head(p)) + .collect(), + attention: Vec::new(), + recurrent: Vec::new(), + prefix: challenge + .prefix_positions(self.receipt.position_start) + .into_iter() + .map(|p| self.prefix.open(stage, p)) + .collect(), + prefix_tokens: if stage == 0 { + self.prefix.tokens.clone() + } else { + Vec::new() + }, + } + }) + .collect(); + Opening { + receipt_id: challenge.receipt_id.clone(), + stages, + } + } + + fn anchor(&self, position: u32) -> AnchorOpening { + AnchorOpening { + position, + token: self.token(position), + residual: encode_f32(&self.at(0, position).residual_in), + path: self.path(0, position, 0).1, + } + } + + fn head(&self, position: u32) -> HeadOpening { + let index = (position - self.receipt.position_start) as usize; + HeadOpening { + position, + residual: encode_f32(&self.at(LAYERS - 1, position).residual_out), + path: self.path(LAYERS - 1, position, 2).1, + logits: Some(encode_f32(&self.logits[index])), + } + } + + /// The toy node's signature of an opening of `challenge`. The receipt + /// must be bound. + pub fn sign_opening(&self, challenge: &Challenge, opening_bytes: &[u8]) -> String { + let bound = turn::verify(&self.receipt, None).expect("a bound receipt"); + turn::sign_opening(&self.node, &bound.turn_root, challenge, opening_bytes) + } + + /// The toy node's signature of attention rows it opened for `blocks`. + pub fn sign_rows(&self, blocks: &BlockChallenge, rows_bytes: &[u8]) -> String { + let bound = turn::verify(&self.receipt, None).expect("a bound receipt"); + turn::sign_rows(&self.node, &bound.turn_root, blocks, rows_bytes) + } +} + +impl Default for Turn { + fn default() -> Self { + Self::new() + } +} + +/// Leaves per position of a stage of one layer. +const SLOTS: u64 = 3; + +/// The tree of the stage holding `layer`: per position, the residual in, +/// the mixing values and the residual out. +fn stage_tree(layer: u32, start: u32, tokens: &[i32], computed: &[Computed]) -> MerkleTree { + debug_assert_eq!(slots_per_position(layer, layer + 1), SLOTS); + let mut leaves = Vec::new(); + for (i, values) in computed.iter().enumerate() { + let position = start + i as u32; + let token = (layer == 0).then(|| tokens[i]); + leaves.extend(position_leaves(layer, position, token, values)); + } + MerkleTree::new(leaves).expect("a turn has positions") +} + +/// The leaves the stage holding `layer` commits at one position: the +/// residual in, the mixing values and the residual out. +fn position_leaves(layer: u32, position: u32, token: Option, values: &Computed) -> [Hash; 3] { + let mixing = values.mixing(); + let decoded = crate::wire::mixing_bytes(&mixing).expect("mixing values"); + let mixing: Vec> = crate::wire::mixing_values(&decoded); + [ + residual_leaf( + position, + layer, + token, + Some(&f32_bytes(&values.residual_in)), + ), + mixing_leaf(position, layer, &mixing), + residual_leaf( + position, + layer + 1, + None, + Some(&f32_bytes(&values.residual_out)), + ), + ] +} diff --git a/crates/skippy-receipts/src/turn.rs b/crates/skippy-receipts/src/turn.rs new file mode 100644 index 00000000..f55306d9 --- /dev/null +++ b/crates/skippy-receipts/src/turn.rs @@ -0,0 +1,642 @@ +//! The signed turn root: one hash over everything a receipt claims, signed +//! by the serving node, and the VRF inputs a client draws from it. +//! +//! The root binds the client's VRF key, so the client is bound to its key +//! before it learns the root, the turn that came before (`parent`), so +//! a conversation's receipts form a chain, and how the node chose its +//! tokens (`sampler`), so a node that says it decoded greedily and did not +//! signs a false statement. A client checks the signature +//! and the root, then derives its challenge from the VRF of the root +//! ([`challenge_input`]) and the rows it checks from the VRF of the +//! opening's bytes ([`rows_input`]). + +use anyhow::{Context, Result, bail}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +use crate::attention::opening::BlockChallenge; +use crate::commitment::{Hash, hex_array}; +use crate::wire::{Challenge, Receipt}; + +const TURN_DOMAIN: &str = "mesh-llm receipts turn v1"; +const OPENING_DOMAIN: &str = "mesh-llm receipts opening v2"; +const ROWS_DOMAIN: &str = "mesh-llm receipts attention rows v2"; + +/// Response header of `POST /receipts/open` that holds the node's hex +/// signature of the opening's bytes ([`sign_opening`]). +pub const OPENING_SIGNATURE_HEADER: &str = "x-receipt-opening-signature"; +const CHALLENGE_PREFIX: &[u8] = b"mesh-llm/receipts/challenge"; +const ROWS_PREFIX: &[u8] = b"mesh-llm/receipts/rows"; + +/// How a receipt names its runtime: the Skippy ABI version and the source +/// the native library was built from ([`skippy_runtime`'s +/// `receipt_runtime_source`]). A verifier whose glue evaluation runs +/// another runtime may not reproduce the node's rounding. +pub fn runtime_identity(major: u32, minor: u32, patch: u32, source: &str) -> String { + format!("skippy-abi {major}.{minor}.{patch}; {source}") +} + +/// The sampler of a turn that took the best logit at every token. +pub const GREEDY: &str = "greedy"; +/// The sampler of any other turn: temperature, penalties or logit biases. +/// The statement is `sampled` followed by a space and a JSON object of the +/// sampler's parameters and seed ([`sampled`]). +pub(crate) const SAMPLED: &str = "sampled"; +/// The `draw` a sampled turn's statement names when a client can replay it: +/// the token at position `i` of the sequence is picked by a uniform that is +/// a function of the stated seed and of `i`, over the candidates the sampler +/// chain kept, in token id order (`head::draw` on the client, the +/// `receipts_draw` sampler on the node). +pub const INDEXED_DRAW: &str = "indexed-v1"; +/// The field of a sampled turn's statement that names what the node built +/// the turn's reasoning-budget sampler from, so a client can replay which +/// tokens the sampler forced (`head::reasoning_budget`): the tag that starts +/// the reasoning (`start`), the tags that end it (`ends`), and the text the +/// chat template placed after the prompt (`prefill`). A turn without such +/// a sampler states none. +pub const REASONING: &str = "reasoning"; + +/// The sampler statement of a turn that sampled with `parameters`. +pub fn sampled(parameters: &serde_json::Value) -> String { + format!("{SAMPLED} {parameters}") +} + +/// The sampler parameters a statement names, `None` for a greedy turn or a +/// statement that names none. +pub fn sampler_parameters(sampler: &str) -> Option { + let parameters = sampler.strip_prefix(SAMPLED)?.strip_prefix(' ')?; + serde_json::from_str(parameters).ok() +} + +/// What binds a receipt to its client and its node. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct TurnBinding { + /// Hex VRF key the client named in its request. + pub client_key: String, + /// Hex turn root of the turn this one continues, as the client named it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// The runtime that served the turn: Skippy ABI and llama.cpp patch + /// queue. An auditor whose glue evaluation does not match it cannot + /// check the glue. + pub runtime: String, + /// How the node chose its tokens: [`GREEDY`], or [`SAMPLED`] with the + /// sampler's parameters and seed. + pub sampler: String, + /// Hex Ed25519 key of the serving node. + pub node_key: String, + /// Hex [`turn_root`] of the receipt. + pub turn_root: String, + /// Hex Ed25519 signature of the turn root under `node_key`. + pub signature: String, +} + +/// What the node binds into a receipt besides its commitments. +#[derive(Clone, Debug)] +pub struct BindingRequest { + pub client_key: [u8; 32], + pub parent: Option, + pub runtime: String, + pub sampler: String, +} + +/// What the binding adds to a receipt's fields in its root. +pub struct RootFields<'a> { + pub client_key: &'a str, + pub parent: Option<&'a str>, + pub runtime: &'a str, + pub sampler: &'a str, + pub node_key: &'a str, +} + +/// The hash over every field of `receipt` but the root and signature. +pub fn turn_root(receipt: &Receipt, fields: &RootFields<'_>) -> Hash { + let mut h = blake3::Hasher::new_derive_key(TURN_DOMAIN); + let text = |h: &mut blake3::Hasher, s: &str| { + h.update(&(s.len() as u64).to_le_bytes()); + h.update(s.as_bytes()); + }; + h.update(&receipt.version.to_le_bytes()); + text(&mut h, &receipt.receipt_id); + text(&mut h, &receipt.model); + h.update(&receipt.position_start.to_le_bytes()); + h.update(&receipt.position_end.to_le_bytes()); + h.update(&receipt.generation_start.to_le_bytes()); + match receipt.final_token { + Some(token) => h.update(&[1]).update(&token.to_le_bytes()), + None => h.update(&[0]), + }; + h.update(&(receipt.tokens.len() as u64).to_le_bytes()); + for token in &receipt.tokens { + h.update(&token.to_le_bytes()); + } + h.update(&(receipt.stages.len() as u64).to_le_bytes()); + for stage in &receipt.stages { + h.update(&stage.stage_index.to_le_bytes()); + h.update(&stage.layer_start.to_le_bytes()); + h.update(&stage.layer_end.to_le_bytes()); + text(&mut h, &stage.root); + h.update(&stage.leaf_count.to_le_bytes()); + text(&mut h, &stage.backend); + h.update(&(stage.cache_types.len() as u64).to_le_bytes()); + for cache_type in &stage.cache_types { + text(&mut h, cache_type); + } + h.update(&(stage.ubatches.len() as u64).to_le_bytes()); + for start in &stage.ubatches { + h.update(&start.to_le_bytes()); + } + match &stage.prefix { + Some(prefix) => { + h.update(&[1]); + text(&mut h, &prefix.root); + h.update(&prefix.positions.to_le_bytes()); + match &prefix.tokens { + Some(tokens) => { + h.update(&[1]); + text(&mut h, tokens); + } + None => { + h.update(&[0]); + } + } + } + None => { + h.update(&[0]); + } + } + match &stage.recurrent_state { + Some(state) => { + h.update(&[1]); + text(&mut h, state); + } + None => { + h.update(&[0]); + } + } + } + text(&mut h, fields.client_key); + match fields.parent { + Some(parent) => { + h.update(&[1]); + text(&mut h, parent); + } + None => { + h.update(&[0]); + } + } + text(&mut h, fields.runtime); + text(&mut h, fields.sampler); + text(&mut h, fields.node_key); + *h.finalize().as_bytes() +} + +/// Binds `receipt` to the request and signs it with the node key. +pub fn bind(receipt: &mut Receipt, request: &BindingRequest, node: &SigningKey) { + let client_key = hex::encode(request.client_key); + let parent = request.parent.map(hex::encode); + let node_key = hex::encode(node.verifying_key().as_bytes()); + let root = turn_root( + receipt, + &RootFields { + client_key: &client_key, + parent: parent.as_deref(), + runtime: &request.runtime, + sampler: &request.sampler, + node_key: &node_key, + }, + ); + let signature = node.sign(&root); + receipt.binding = Some(TurnBinding { + client_key, + parent, + runtime: request.runtime.clone(), + sampler: request.sampler.clone(), + node_key, + turn_root: hex::encode(root), + signature: hex::encode(signature.to_bytes()), + }); +} + +/// A receipt's checked binding. +#[derive(Clone, Debug)] +pub struct VerifiedBinding { + pub turn_root: Hash, + pub client_key: [u8; 32], + pub node_key: [u8; 32], +} + +/// Checks that `receipt` is bound and signed, and recomputes its root. +/// `client_key` is the key the client named, when it checks its own +/// receipt. +pub fn verify(receipt: &Receipt, client_key: Option<&[u8; 32]>) -> Result { + let binding = receipt + .binding + .as_ref() + .context("the receipt is not bound to a client key and signed")?; + let named = + crate::vrf::key_from_hex(&binding.client_key).context("the receipt's client key")?; + if let Some(expected) = client_key + && expected != &named + { + bail!("the receipt names another client key"); + } + let root = turn_root( + receipt, + &RootFields { + client_key: &binding.client_key, + parent: binding.parent.as_deref(), + runtime: &binding.runtime, + sampler: &binding.sampler, + node_key: &binding.node_key, + }, + ); + if hex::encode(root) != binding.turn_root { + bail!("the receipt's turn root does not match its fields"); + } + let node_key = hex_array(&binding.node_key, "the receipt's node key")?; + verify_signed(&node_key, &root, &binding.signature) + .context("the node's signature of the turn root does not verify")?; + Ok(VerifiedBinding { + turn_root: root, + client_key: named, + node_key, + }) +} + +/// What a node signs for an opening: its turn root, the challenge it +/// answers, and the opening's bytes as sent. The opened matmul columns come +/// from a replay and are in no Merkle tree, so without the signature a +/// client could show an opening the node never sent. Without the challenge +/// under the signature, a client could show an honest opening as the +/// answer to a challenge the node was never sent. +fn opening_digest(turn_root: &Hash, challenge: &Challenge, opening_bytes: &[u8]) -> Hash { + signed_digest( + OPENING_DOMAIN, + turn_root, + &challenge.digest(), + opening_bytes, + ) +} + +fn signed_digest(domain: &str, turn_root: &Hash, request: &Hash, answer_bytes: &[u8]) -> Hash { + let mut h = blake3::Hasher::new_derive_key(domain); + h.update(turn_root); + h.update(request); + h.update(blake3::hash(answer_bytes).as_bytes()); + *h.finalize().as_bytes() +} + +/// The node's hex signature of its opening of `challenge` for the turn +/// `turn_root`. +pub fn sign_opening( + node: &SigningKey, + turn_root: &Hash, + challenge: &Challenge, + opening_bytes: &[u8], +) -> String { + hex::encode( + node.sign(&opening_digest(turn_root, challenge, opening_bytes)) + .to_bytes(), + ) +} + +/// Checks the node's signature of its opening of `challenge` for a bound +/// receipt. +pub fn verify_opening( + binding: &VerifiedBinding, + challenge: &Challenge, + opening_bytes: &[u8], + signature: &str, +) -> Result<()> { + verify_signed( + &binding.node_key, + &opening_digest(&binding.turn_root, challenge, opening_bytes), + signature, + ) + .context("the node's signature of the opening does not verify") +} + +/// The node's hex signature of the attention rows it opened for `blocks` +/// of the turn `turn_root`, which a client keeps as evidence like an +/// opening. +pub fn sign_rows( + node: &SigningKey, + turn_root: &Hash, + blocks: &BlockChallenge, + rows_bytes: &[u8], +) -> String { + hex::encode( + node.sign(&signed_digest( + ROWS_DOMAIN, + turn_root, + &blocks.digest(), + rows_bytes, + )) + .to_bytes(), + ) +} + +/// Checks the node's signature of the attention rows it opened for +/// `blocks` of a bound receipt. +pub fn verify_rows( + binding: &VerifiedBinding, + blocks: &BlockChallenge, + rows_bytes: &[u8], + signature: &str, +) -> Result<()> { + let digest = signed_digest( + ROWS_DOMAIN, + &binding.turn_root, + &blocks.digest(), + rows_bytes, + ); + verify_signed(&binding.node_key, &digest, signature) + .context("the node's signature of the attention rows does not verify") +} + +const CANNOT_OPEN_DOMAIN: &str = "mesh-llm receipts cannot open v1"; + +/// The node's hex signature of its answer that it can no longer open +/// `request`, the digest of the challenge or block challenge it was sent +/// ([`Challenge::digest`], [`BlockChallenge::digest`]), for the turn +/// `turn_root`. `answer_bytes` are the bytes of the +/// [`crate::wire::CannotOpen`] as sent. A client keeps it to show that the +/// node itself said it could not open the turn. +pub fn sign_cannot_open( + node: &SigningKey, + turn_root: &Hash, + request: &Hash, + answer_bytes: &[u8], +) -> String { + hex::encode( + node.sign(&signed_digest( + CANNOT_OPEN_DOMAIN, + turn_root, + request, + answer_bytes, + )) + .to_bytes(), + ) +} + +/// Checks the node's signature of a "cannot open" answer to `request` for a +/// bound receipt. +pub fn verify_cannot_open( + binding: &VerifiedBinding, + request: &Hash, + answer_bytes: &[u8], + signature: &str, +) -> Result<()> { + let digest = signed_digest( + CANNOT_OPEN_DOMAIN, + &binding.turn_root, + request, + answer_bytes, + ); + verify_signed(&binding.node_key, &digest, signature) + .context("the node's signature of its cannot-open answer does not verify") +} + +fn verify_signed(node_key: &[u8; 32], digest: &Hash, signature: &str) -> Result<()> { + let verifying = VerifyingKey::from_bytes(node_key).context("the node key")?; + let bytes = hex_array(signature, "a signature")?; + Ok(verifying.verify_strict(digest, &Signature::from_bytes(&bytes))?) +} + +/// Checks that `next` continues the conversation of `previous`, both bound +/// and verified: `next` names the root of `previous` as its parent, for the +/// same client key and node. A client keeps the chain of a conversation so +/// a node cannot present a turn as continuing one it never served. +pub fn verify_chain( + previous: &Receipt, + previous_binding: &VerifiedBinding, + next: &Receipt, + next_binding: &VerifiedBinding, +) -> Result<()> { + let parent = next + .binding + .as_ref() + .and_then(|b| b.parent.as_deref()) + .context("the receipt names no parent turn")?; + if hex_array::<32>(parent, "the parent turn root")? != previous_binding.turn_root { + bail!( + "receipt {} continues another turn than receipt {}", + next.receipt_id, + previous.receipt_id + ); + } + if next_binding.client_key != previous_binding.client_key { + bail!("the turns name different client keys"); + } + if next_binding.node_key != previous_binding.node_key { + bail!("the turns were signed by different nodes"); + } + Ok(()) +} + +/// The VRF input the challenge is drawn from. +pub fn challenge_input(turn_root: &Hash) -> Vec { + [CHALLENGE_PREFIX, turn_root].concat() +} + +/// The VRF input the checked rows are drawn from: the opening as the +/// client received it. +pub fn rows_input(opening_bytes: &[u8]) -> Vec { + rows_input_of_digest(blake3::hash(opening_bytes).as_bytes()) +} + +/// [`rows_input`] from the BLAKE3 digest of the opening's bytes. +pub fn rows_input_of_digest(opening_digest: &Hash) -> Vec { + [ROWS_PREFIX, opening_digest].concat() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wire::{RECEIPT_VERSION, StageCommitment}; + + fn receipt() -> Receipt { + Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 3, + tokens: vec![1, 2, 3], + generation_start: 2, + final_token: Some(4), + stages: vec![StageCommitment { + stage_index: 0, + layer_start: 0, + layer_end: 2, + root: "ab".into(), + leaf_count: 15, + backend: "CPU".into(), + cache_types: vec!["f16".into()], + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }], + binding: None, + } + } + + fn request() -> BindingRequest { + BindingRequest { + client_key: crate::vrf::SecretKey::from_seed([9; 32]).public(), + parent: None, + runtime: "skippy 0.1.77".into(), + sampler: GREEDY.into(), + } + } + + #[test] + fn a_bound_receipt_verifies() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut r = receipt(); + bind(&mut r, &request(), &node); + let verified = verify(&r, Some(&request().client_key)).unwrap(); + assert_eq!(verified.node_key, node.verifying_key().to_bytes()); + } + + #[test] + fn a_turn_chains_to_its_parent() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut first = receipt(); + bind(&mut first, &request(), &node); + let first_bound = verify(&first, None).unwrap(); + let chained = |parent: Hash, signer: &SigningKey| { + let mut next = receipt(); + next.receipt_id = "r2".into(); + let request = BindingRequest { + parent: Some(parent), + ..request() + }; + bind(&mut next, &request, signer); + let bound = verify(&next, None).unwrap(); + (next, bound) + }; + let (next, bound) = chained(first_bound.turn_root, &node); + verify_chain(&first, &first_bound, &next, &bound).unwrap(); + let (other, bound) = chained([1; 32], &node); + assert!(verify_chain(&first, &first_bound, &other, &bound).is_err()); + let (moved, bound) = chained(first_bound.turn_root, &SigningKey::from_bytes(&[6; 32])); + assert!(verify_chain(&first, &first_bound, &moved, &bound).is_err()); + assert!(verify_chain(&first, &first_bound, &first, &first_bound).is_err()); + } + + #[test] + fn every_field_is_bound() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut bound = receipt(); + bind(&mut bound, &request(), &node); + type Change = Box; + let changes: Vec = vec![ + Box::new(|r| r.tokens[1] = 9), + Box::new(|r| r.final_token = None), + Box::new(|r| r.generation_start = 1), + Box::new(|r| r.stages[0].root = "ac".into()), + Box::new(|r| r.stages[0].backend = "CUDA0".into()), + Box::new(|r| r.stages[0].ubatches = vec![0, 3]), + Box::new(|r| { + r.stages[0].prefix = Some(crate::wire::PrefixCommitment { + root: "ad".into(), + positions: 3, + tokens: None, + }); + }), + Box::new(|r| { + r.stages[0].prefix = Some(crate::wire::PrefixCommitment { + root: String::new(), + positions: 0, + tokens: Some("ae".into()), + }); + }), + Box::new(|r| r.model = "n".into()), + Box::new(|r| r.binding.as_mut().unwrap().runtime = "other".into()), + Box::new(|r| r.binding.as_mut().unwrap().sampler = SAMPLED.into()), + Box::new(|r| r.binding.as_mut().unwrap().parent = Some("00".into())), + ]; + for change in changes { + let mut r = bound.clone(); + change(&mut r); + assert!(verify(&r, None).is_err()); + } + } + + #[test] + fn an_opening_is_signed_for_its_turn() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut r = receipt(); + bind(&mut r, &request(), &node); + let bound = verify(&r, None).unwrap(); + let challenge = Challenge { + receipt_id: r.receipt_id.clone(), + picks: vec![crate::wire::Pick { + layer: 1, + positions: vec![0, 2], + }], + proof: Some("ab".into()), + head: vec![2], + attention: Vec::new(), + }; + let signature = sign_opening(&node, &bound.turn_root, &challenge, b"{}"); + verify_opening(&bound, &challenge, b"{}", &signature).unwrap(); + assert!(verify_opening(&bound, &challenge, b"{ }", &signature).is_err()); + let other_turn = VerifiedBinding { + turn_root: [0; 32], + ..bound.clone() + }; + assert!(verify_opening(&other_turn, &challenge, b"{}", &signature).is_err()); + // an opening is evidence only of the challenge the node answered + let mut other_picks = challenge.clone(); + other_picks.picks[0].positions = vec![0, 1]; + assert!(verify_opening(&bound, &other_picks, b"{}", &signature).is_err()); + let mut other_head = challenge.clone(); + other_head.head = vec![1]; + assert!(verify_opening(&bound, &other_head, b"{}", &signature).is_err()); + let mut other_proof = challenge.clone(); + other_proof.proof = None; + assert!(verify_opening(&bound, &other_proof, b"{}", &signature).is_err()); + } + + #[test] + fn attention_rows_are_signed_for_the_blocks_asked() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut r = receipt(); + bind(&mut r, &request(), &node); + let bound = verify(&r, None).unwrap(); + let blocks = BlockChallenge { + receipt_id: r.receipt_id.clone(), + picks: vec![crate::attention::opening::BlockPick { + position: 2, + layer: 1, + blocks: vec![0, 3], + }], + proof: Some("cd".into()), + }; + let signature = sign_rows(&node, &bound.turn_root, &blocks, b"{}"); + verify_rows(&bound, &blocks, b"{}", &signature).unwrap(); + assert!(verify_rows(&bound, &blocks, b"{ }", &signature).is_err()); + let mut other = blocks.clone(); + other.picks[0].blocks = vec![0, 2]; + assert!(verify_rows(&bound, &other, b"{}", &signature).is_err()); + } + + #[test] + fn another_client_key_or_node_signature_fails() { + let node = SigningKey::from_bytes(&[5; 32]); + let mut r = receipt(); + bind(&mut r, &request(), &node); + assert!(verify(&r, Some(&[1; 32])).is_err()); + // a node that re-signs with its own key must also rewrite node_key, + // which changes the root + let mut forged = r.clone(); + let other = SigningKey::from_bytes(&[6; 32]); + let root = crate::vrf::key_from_hex(&forged.binding.as_ref().unwrap().turn_root).unwrap(); + forged.binding.as_mut().unwrap().signature = hex::encode(other.sign(&root).to_bytes()); + assert!(verify(&forged, None).is_err()); + assert!(verify(&receipt(), None).is_err()); + } +} diff --git a/crates/skippy-receipts/src/vrf.rs b/crates/skippy-receipts/src/vrf.rs new file mode 100644 index 00000000..ac46bd95 --- /dev/null +++ b/crates/skippy-receipts/src/vrf.rs @@ -0,0 +1,383 @@ +//! ECVRF-EDWARDS25519-SHA512-TAI (RFC 9381), the verifiable random function +//! a client draws its challenges and checked rows from. +//! +//! The VRF gives one output per key and input, and anyone with the public +//! key can check it. So a client cannot draw a challenge again until an +//! honest node's rare outliers fail it, and a node that learns the output +//! for one input learns nothing about another. A plain Ed25519 signature +//! would not do: its signer chooses the nonce and can make many valid +//! signatures of one message. +//! +//! Only the TAI suite (try and increment) is implemented, with +//! `validate_key = TRUE`. Points are decoded strictly: an encoding must be +//! canonical, so a proof has one encoding. + +use anyhow::{Result, bail}; +use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint}; +use curve25519_dalek::scalar::{Scalar, clamp_integer}; +use curve25519_dalek::traits::IsIdentity; +use sha2::{Digest, Sha512}; + +const SUITE: u8 = 0x03; +/// Bytes of a proof: Gamma, c and s. +pub const PROOF_LEN: usize = 32 + 16 + 32; +/// Bytes of a VRF output. +pub(crate) const OUTPUT_LEN: usize = 64; + +pub type Proof = [u8; PROOF_LEN]; +pub type Output = [u8; OUTPUT_LEN]; + +/// A VRF secret key: the 32-byte seed of RFC 8032, section 5.1.5. +/// +/// Whoever holds it can draw the client's challenges before the client +/// does. So it cannot be copied or read out, and its secrets are wiped +/// when it is dropped. +pub struct SecretKey { + seed: [u8; 32], + scalar: Scalar, + public: [u8; 32], +} + +impl Drop for SecretKey { + fn drop(&mut self) { + self.wipe(); + } +} + +impl std::fmt::Debug for SecretKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SecretKey") + .field("public", &hex::encode(self.public)) + .finish_non_exhaustive() + } +} + +impl SecretKey { + pub fn from_seed(seed: [u8; 32]) -> Self { + let hashed = Sha512::digest(seed); + let mut low = [0u8; 32]; + low.copy_from_slice(&hashed[..32]); + let scalar = Scalar::from_bytes_mod_order(clamp_integer(low)); + let public = EdwardsPoint::mul_base(&scalar).compress().to_bytes(); + Self { + seed, + scalar, + public, + } + } + + pub fn generate(rng: &mut impl rand::Rng) -> Self { + let mut seed = [0u8; 32]; + rng.fill_bytes(&mut seed); + Self::from_seed(seed) + } + + pub fn public(&self) -> [u8; 32] { + self.public + } + + /// Overwrites the seed and the scalar. The fence and the opaque read + /// keep the compiler from dropping writes to memory about to be freed. + fn wipe(&mut self) { + self.seed = [0; 32]; + self.scalar = Scalar::ZERO; + std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst); + std::hint::black_box((&self.seed, &self.scalar)); + } + + /// The proof for `alpha` (RFC 9381, section 5.1). + pub fn prove(&self, alpha: &[u8]) -> Proof { + let h = encode_to_curve(&self.public, alpha); + let h_string = h.compress().to_bytes(); + let gamma = self.scalar * h; + let hashed = Sha512::digest(self.seed); + let k_string: [u8; 64] = Sha512::new() + .chain_update(&hashed[32..]) + .chain_update(h_string) + .finalize() + .into(); + let k = Scalar::from_bytes_mod_order_wide(&k_string); + let c = challenge( + &self.public, + &h, + &gamma, + &EdwardsPoint::mul_base(&k), + &(k * h), + ); + let s = k + c * self.scalar; + let mut proof = [0u8; PROOF_LEN]; + proof[..32].copy_from_slice(&gamma.compress().to_bytes()); + proof[32..48].copy_from_slice(&c.to_bytes()[..16]); + proof[48..].copy_from_slice(&s.to_bytes()); + proof + } + + /// The output for `alpha`, with its proof. + pub fn evaluate(&self, alpha: &[u8]) -> (Output, Proof) { + let proof = self.prove(alpha); + let gamma = decode_point(&proof[..32]).expect("a proof this key made"); + (proof_to_hash(&gamma), proof) + } +} + +/// Checks `proof` for `alpha` under `public` and returns the VRF output +/// (RFC 9381, section 5.3). +pub fn verify(public: &[u8; 32], alpha: &[u8], proof: &Proof) -> Result { + let Some(y) = decode_point(public) else { + bail!("the VRF key is not a point"); + }; + if y.mul_by_cofactor().is_identity() { + bail!("the VRF key has small order"); + } + let Some(gamma) = decode_point(&proof[..32]) else { + bail!("the VRF proof's Gamma is not a point"); + }; + let mut c_bytes = [0u8; 32]; + c_bytes[..16].copy_from_slice(&proof[32..48]); + let c = Scalar::from_bytes_mod_order(c_bytes); + let mut s_bytes = [0u8; 32]; + s_bytes.copy_from_slice(&proof[48..]); + let Some(s) = Option::::from(Scalar::from_canonical_bytes(s_bytes)) else { + bail!("the VRF proof's s is not below the group order"); + }; + let h = encode_to_curve(public, alpha); + // U = s*B - c*Y and V = s*H - c*Gamma + let u = EdwardsPoint::vartime_double_scalar_mul_basepoint(&-c, &y, &s); + let v = s * h - c * gamma; + if challenge(public, &h, &gamma, &u, &v) != c { + bail!("the VRF proof does not verify"); + } + Ok(proof_to_hash(&gamma)) +} + +fn proof_to_hash(gamma: &EdwardsPoint) -> Output { + Sha512::new() + .chain_update([SUITE, 0x03]) + .chain_update(gamma.mul_by_cofactor().compress().to_bytes()) + .chain_update([0x00]) + .finalize() + .into() +} + +/// ECVRF_encode_to_curve_try_and_increment, with the public key as salt. +fn encode_to_curve(public: &[u8; 32], alpha: &[u8]) -> EdwardsPoint { + for ctr in 0..=u8::MAX { + let hash = Sha512::new() + .chain_update([SUITE, 0x01]) + .chain_update(public) + .chain_update(alpha) + .chain_update([ctr, 0x00]) + .finalize(); + if let Some(point) = decode_point(&hash[..32]) { + let point = point.mul_by_cofactor(); + if !point.is_identity() { + return point; + } + } + } + // each attempt succeeds with probability about 1/2 + unreachable!("try and increment failed 256 times") +} + +/// The challenge: the first 16 bytes of the hash of five points. +fn challenge( + y: &[u8; 32], + h: &EdwardsPoint, + gamma: &EdwardsPoint, + u: &EdwardsPoint, + v: &EdwardsPoint, +) -> Scalar { + let digest = Sha512::new() + .chain_update([SUITE, 0x02]) + .chain_update(y) + .chain_update(h.compress().to_bytes()) + .chain_update(gamma.compress().to_bytes()) + .chain_update(u.compress().to_bytes()) + .chain_update(v.compress().to_bytes()) + .chain_update([0x00]) + .finalize(); + let mut c = [0u8; 32]; + c[..16].copy_from_slice(&digest[..16]); + Scalar::from_bytes_mod_order(c) +} + +/// RFC 8032 decoding, section 5.1.3: the encoding must be canonical. +fn decode_point(bytes: &[u8]) -> Option { + let compressed = CompressedEdwardsY::from_slice(bytes).ok()?; + let point = compressed.decompress()?; + (point.compress() == compressed).then_some(point) +} + +pub fn proof_from_hex(text: &str) -> Result { + let bytes = hex::decode(text)?; + Proof::try_from(bytes.as_slice()) + .map_err(|_| anyhow::anyhow!("a VRF proof has {PROOF_LEN} bytes, not {}", bytes.len())) +} + +pub fn key_from_hex(text: &str) -> Result<[u8; 32]> { + crate::commitment::hex_array(text, "a VRF key") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bytes(text: &str) -> [u8; N] { + hex::decode(text).unwrap().try_into().unwrap() + } + + /// RFC 9381, appendix B.3, examples 16 to 18. + const VECTORS: [(&str, &str, &str, &str, &str); 3] = [ + ( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + "", + "8657106690b5526245a92b003bb079ccd1a92130477671f6fc01ad16f26f723f\ + 26f8a57ccaed74ee1b190bed1f479d9727d2d0f9b005a6e456a35d4fb0daab12\ + 68a1b0db10836d9826a528ca76567805", + "90cf1df3b703cce59e2a35b925d411164068269d7b2d29f3301c03dd757876ff\ + 66b71dda49d2de59d03450451af026798e8f81cd2e333de5cdf4f3e140fdd8ae", + ), + ( + "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + "72", + "f3141cd382dc42909d19ec5110469e4feae18300e94f304590abdced48aed593\ + 3bf0864a62558b3ed7f2fea45c92a465301b3bbf5e3e54ddf2d935be3b67926d\ + a3ef39226bbc355bdc9850112c8f4b02", + "eb4440665d3891d668e7e0fcaf587f1b4bd7fbfe99d0eb2211ccec90496310eb\ + 5e33821bc613efb94db5e5b54c70a848a0bef4553a41befc57663b56373a5031", + ), + ( + "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + "af82", + "9bc0f79119cc5604bf02d23b4caede71393cedfbb191434dd016d30177ccbf80\ + 96bb474e53895c362d8628ee9f9ea3c0e52c7a5c691b6c18c9979866568add7a\ + 2d41b00b05081ed0f58ee5e31b3a970e", + "645427e5d00c62a23fb703732fa5d892940935942101e456ecca7bb217c61c45\ + 2118fec1219202a0edcf038bb6373241578be7217ba85a2687f7a0310b2df19f", + ), + ]; + + fn unwrap_hex(text: &str) -> String { + text.split_whitespace().collect() + } + + #[test] + fn matches_the_rfc_vectors() { + for (sk, pk, alpha, pi, beta) in VECTORS { + let key = SecretKey::from_seed(bytes(sk)); + assert_eq!(hex::encode(key.public()), pk); + let alpha = hex::decode(alpha).unwrap(); + let (output, proof) = key.evaluate(&alpha); + assert_eq!(hex::encode(proof), unwrap_hex(pi)); + assert_eq!(hex::encode(output), unwrap_hex(beta)); + assert_eq!(verify(&bytes(pk), &alpha, &proof).unwrap(), output); + } + } + + #[test] + fn a_changed_input_proof_or_key_fails() { + let key = SecretKey::from_seed([7; 32]); + let proof = key.prove(b"root"); + assert!(verify(&key.public(), b"root!", &proof).is_err()); + for byte in [0, 40, 70] { + let mut bad = proof; + bad[byte] ^= 1; + assert!(verify(&key.public(), b"root", &bad).is_err(), "byte {byte}"); + } + let other = SecretKey::from_seed([8; 32]); + assert!(verify(&other.public(), b"root", &proof).is_err()); + } + + #[test] + fn small_order_keys_are_refused() { + // the identity point + let mut identity = [0u8; 32]; + identity[0] = 1; + let proof = SecretKey::from_seed([1; 32]).prove(b"x"); + assert!(verify(&identity, b"x", &proof).is_err()); + // and the seven other points of order 1, 2, 4 and 8 + let torsion = curve25519_dalek::constants::EIGHT_TORSION; + let encodings: std::collections::BTreeSet<[u8; 32]> = + torsion.iter().map(|p| p.compress().to_bytes()).collect(); + assert_eq!(encodings.len(), 8); + assert!(encodings.contains(&identity)); + for key in encodings { + let error = verify(&key, b"x", &proof).unwrap_err(); + assert!(error.to_string().contains("small order"), "{error}"); + } + } + + #[test] + fn a_small_order_gamma_does_not_verify() { + // it would give every input of the key the same output + let key = SecretKey::from_seed([3; 32]); + for point in curve25519_dalek::constants::EIGHT_TORSION { + let mut proof = key.prove(b"x"); + proof[..32].copy_from_slice(&point.compress().to_bytes()); + assert!(verify(&key.public(), b"x", &proof).is_err()); + } + } + + #[test] + fn a_non_canonical_gamma_is_refused() { + let key = SecretKey::from_seed([3; 32]); + // y = p + 1, which reduces to the identity's y = 1 + let mut above_p = [0xffu8; 32]; + above_p[0] = 0xee; + above_p[31] = 0x7f; + // x = 0 with the sign bit set: "minus zero" + let mut minus_zero = [0u8; 32]; + minus_zero[0] = 1; + minus_zero[31] = 0x80; + for gamma in [above_p, minus_zero] { + let mut proof = key.prove(b"x"); + proof[..32].copy_from_slice(&gamma); + let error = verify(&key.public(), b"x", &proof).unwrap_err(); + assert!( + error.to_string().contains("Gamma is not a point"), + "{error}" + ); + // a key encoded that way is refused as well + let proof = key.prove(b"x"); + let error = verify(&gamma, b"x", &proof).unwrap_err(); + assert!(error.to_string().contains("key is not a point"), "{error}"); + } + } + + #[test] + fn a_dropped_key_wipes_its_secrets() { + let mut key = SecretKey::from_seed([7; 32]); + let public = key.public(); + assert_ne!(key.scalar, Scalar::ZERO); + key.wipe(); + assert_eq!(key.seed, [0; 32]); + assert_eq!(key.scalar, Scalar::ZERO); + // the public half is no secret + assert_eq!(key.public(), public); + assert!(!format!("{key:?}").contains("0707")); + } + + #[test] + fn a_non_canonical_s_is_refused() { + let key = SecretKey::from_seed([3; 32]); + let mut proof = key.prove(b"x"); + // s + q has the same value mod q but is not canonical + let s = Scalar::from_canonical_bytes(proof[48..].try_into().unwrap()).unwrap(); + let q_bytes = + bytes::<32>("edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"); + let mut sum = [0u8; 32]; + let mut carry = 0u16; + for i in 0..32 { + let v = u16::from(s.to_bytes()[i]) + u16::from(q_bytes[i]) + carry; + sum[i] = v as u8; + carry = v >> 8; + } + if carry == 0 { + proof[48..].copy_from_slice(&sum); + assert!(verify(&key.public(), b"x", &proof).is_err()); + } + } +} diff --git a/crates/skippy-receipts/src/weights.rs b/crates/skippy-receipts/src/weights.rs new file mode 100644 index 00000000..62a798da --- /dev/null +++ b/crates/skippy-receipts/src/weights.rs @@ -0,0 +1,541 @@ +//! Reads the claimed GGUF's header and individual weight rows, from a local +//! file or any ranged byte source (for example Hugging Face range requests). +//! +//! The node that issued a receipt names the claimed GGUF, so the file is +//! read as hostile input: the header strictly (`header`), and every read +//! within the [`limits`] of this client. + +use std::collections::BTreeMap; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::Path; +use std::sync::Mutex; + +use anyhow::{Context, Result, bail}; + +mod header; +pub mod limits; + +use header::{FIRST_READ, SHARD_FIRST_READ, parse_header, tensor_bytes}; +pub use header::{MetaArray, TokenList}; +use limits::{FetchBudget, MAX_HEADER_BYTES, MAX_ROW_VALUES, MAX_SHARDS, refuse}; + +/// Random access to the GGUF bytes. +pub trait ByteSource: Send + Sync { + fn read_at(&self, offset: u64, len: u64) -> Result>; + fn size(&self) -> u64; + /// Readies `ranges`, `(offset, len)` each, so later reads of them are + /// local. A local file holds every byte already. + fn prefetch(&self, _ranges: &[(u64, u64)]) -> Result<()> { + Ok(()) + } + /// Reads bytes needed once, which a sparse copy does not keep. + fn read_once(&self, offset: u64, len: u64) -> Result> { + self.read_at(offset, len) + } + /// Bytes that reading `ranges` would fetch from elsewhere, counting + /// whatever the fetch joins between them. A local file holds every + /// byte already. + fn missing_bytes(&self, _ranges: &[(u64, u64)]) -> Result { + Ok(0) + } +} + +pub struct LocalFile { + file: Mutex, + size: u64, +} + +impl LocalFile { + pub fn open(path: &Path) -> Result { + let file = File::open(path).with_context(|| format!("open {}", path.display()))?; + let size = file.metadata()?.len(); + Ok(Self { + file: Mutex::new(file), + size, + }) + } +} + +impl ByteSource for LocalFile { + fn read_at(&self, offset: u64, len: u64) -> Result> { + if offset.checked_add(len).is_none_or(|end| end > self.size) { + bail!( + "bytes {offset}+{len} are past the end of the file ({} bytes)", + self.size + ); + } + let mut file = self + .file + .lock() + .map_err(|_| anyhow::anyhow!("file lock poisoned"))?; + file.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0u8; usize::try_from(len)?]; + file.read_exact(&mut buf)?; + Ok(buf) + } + + fn size(&self) -> u64 { + self.size + } +} + +/// A source whose reads take what they fetch from a budget first: the +/// header's reads, which come before the file is a [`WeightFile`]. +struct Charged<'a> { + source: &'a dyn ByteSource, + budget: &'a FetchBudget, +} + +impl ByteSource for Charged<'_> { + fn read_at(&self, offset: u64, len: u64) -> Result> { + match self.source.missing_bytes(&[(offset, len)])? { + 0 => {} + missing => self.budget.charge(missing)?, + } + self.source.read_at(offset, len) + } + + fn size(&self) -> u64 { + self.source.size() + } +} + +use crate::dequant::dequantize_row; +use crate::ggml_types::type_layout; +use crate::shards::Shards; + +#[derive(Clone, Debug)] +pub struct TensorInfo { + pub name: String, + pub dims: Vec, + pub ggml_type: u32, + /// Absolute file offset of the tensor data. + pub offset: u64, +} + +impl TensorInfo { + /// Values per row (the matmul's K). + pub fn row_len(&self) -> u64 { + self.dims.first().copied().unwrap_or(0) + } + + /// Rows (the matmul's M). + pub fn rows(&self) -> u64 { + self.dims.get(1).copied().unwrap_or(1) + } + + /// Bytes of one row, which is whole blocks of the tensor's type and + /// never empty. + pub fn row_bytes(&self) -> Result { + let (block, bytes) = type_layout(self.ggml_type) + .with_context(|| format!("{}: unknown ggml type {}", self.name, self.ggml_type))?; + let len = self.row_len(); + if len == 0 || !len.is_multiple_of(block) { + bail!( + "{}: a row of {len} values is not whole blocks of {block}", + self.name + ); + } + (len / block) + .checked_mul(bytes) + .with_context(|| format!("{}: the size of a row does not fit", self.name)) + } + + /// Rows over every dimension past the first. + pub(crate) fn row_count(&self) -> Result { + self.dims + .iter() + .skip(1) + .try_fold(1u64, |rows, &dim| rows.checked_mul(dim)) + .with_context(|| format!("{}: the number of rows does not fit", self.name)) + } + + /// Bytes of the whole tensor. A tensor of a type the runtime does not + /// load, or of a size that does not fit, is refused, never sized zero: + /// a sparse copy would leave it a hole. + pub fn total_bytes(&self) -> Result { + tensor_bytes(&self.name, &self.dims, self.ggml_type) + } + + pub fn layer(&self) -> Option { + self.name + .strip_prefix("blk.")? + .split('.') + .next()? + .parse() + .ok() + } + + pub fn is_matrix(&self) -> bool { + self.dims.len() >= 2 && self.dims[1] > 1 && self.name.ends_with(".weight") + } +} + +/// A scalar GGUF metadata value. Arrays are skipped, except the list of +/// suppressed tokens ([`WeightFile::suppressed_tokens`]). +#[derive(Clone, Debug, PartialEq)] +pub enum MetaValue { + Int(u64), + Float(f64), + Str(String), + Tokens(Vec), +} + +/// The claimed model: header metadata and tensor directory. +pub struct WeightFile { + source: Box, + pub tensors: BTreeMap, + pub metadata: BTreeMap, + /// The metadata arrays a check reads before the native loader sees the + /// file: the vocabulary, per-layer counts, rope sections. + pub arrays: BTreeMap, + pub header_bytes: u64, + /// What the reads after the header may still fetch of a remote file. + budget: FetchBudget, +} + +impl WeightFile { + /// Reads the header of the GGUF in `source`, a file held whole: it may + /// fetch nothing ([`Self::open_with_budget`] is for a remote file). + pub fn open(source: Box) -> Result { + Self::open_with_budget(source, 0) + } + + /// Reads the header of the GGUF in `source`, strictly: a file the + /// runtime's loader would not take, or one past the + /// [limits](limits), is refused with [`limits::CannotAudit`]. The reads + /// may fetch `budget` bytes of a remote file, the header's included + /// ([`limits::AUDIT_FETCH_BUDGET`] for an audit). + pub fn open_with_budget(source: Box, budget: u64) -> Result { + let budget = FetchBudget::new(budget); + let charged = Charged { + source: source.as_ref(), + budget: &budget, + }; + let header = parse_header(&charged, FIRST_READ, MAX_HEADER_BYTES)?; + Ok(Self { + source, + tensors: header.tensors, + metadata: header.metadata, + arrays: header.arrays, + header_bytes: header.data_start, + budget, + }) + } + + /// Opens a split GGUF held whole from its shards, in order + /// ([`Self::open_shards_with_budget`]). + pub fn open_shards(shards: Vec>) -> Result { + Self::open_shards_with_budget(shards, 0) + } + + /// Opens a split GGUF from its shards, in order. The first shard's + /// metadata describes the model; each tensor sits at its offset in the + /// shards end to end ([`Shards`]), so ranges name bytes of the whole. + /// The reads may fetch `budget` bytes, as [`Self::open_with_budget`]. + pub fn open_shards_with_budget(shards: Vec>, budget: u64) -> Result { + if shards.is_empty() || shards.len() > MAX_SHARDS { + return refuse(format!( + "it is split into {} shards, not 1 to {MAX_SHARDS}", + shards.len() + )); + } + let source = Shards::new(shards)?; + let budget = FetchBudget::new(budget); + let count = source.parts().count() as u64; + let mut tensors = BTreeMap::new(); + let mut metadata = BTreeMap::new(); + let mut arrays = BTreeMap::new(); + let mut header_bytes = 0; + // the headers of all the shards share the limit of one + let mut headers_left = MAX_HEADER_BYTES; + for (index, (base, shard)) in source.parts().enumerate() { + let first_read = if index == 0 { + FIRST_READ + } else { + SHARD_FIRST_READ + }; + let charged = Charged { + source: shard, + budget: &budget, + }; + let header = parse_header(&charged, first_read, headers_left) + .with_context(|| format!("read shard {}", index + 1))?; + headers_left = headers_left.saturating_sub(header.header_bytes); + check_shard(&header.metadata, index as u64, count)?; + if index == 0 { + metadata = header.metadata; + arrays = header.arrays; + header_bytes = header.data_start; + } + for (name, mut info) in header.tensors { + // a shard's tensors end inside it, so this fits + info.offset = info + .offset + .checked_add(base) + .with_context(|| format!("tensor {name} is past any offset"))?; + if tensors.insert(name.clone(), info).is_some() { + return refuse(format!("tensor {name} is in two of its shards")); + } + } + if tensors.len() as u64 > limits::MAX_TENSORS { + return refuse(format!( + "its shards list more than {} tensors", + limits::MAX_TENSORS + )); + } + } + if let Some(MetaValue::Int(expected)) = metadata.get("split.tensors.count") + && *expected != tensors.len() as u64 + { + return refuse(format!( + "its shards hold {} tensors, not the {expected} the first says", + tensors.len() + )); + } + Ok(Self { + source: Box::new(source), + tensors, + metadata, + arrays, + header_bytes, + budget, + }) + } + + /// Lets the reads from now on fetch `bytes` of a remote file, then + /// refuse with [`limits::CannotAudit`]. A local file is never fetched, + /// and bytes a sparse copy holds cost nothing. Without this the budget + /// is the one the file opened with. + pub fn set_fetch_budget(&self, bytes: u64) { + self.budget.set(bytes); + } + + /// Starts the fetch budget over, for the next audit against a file + /// that stays open. + pub fn reset_fetch_budget(&self) { + self.budget.reset(); + } + + /// Bytes fetched of a remote file since the budget was set or started + /// over, by the reads that count against it. + pub fn fetched_bytes(&self) -> u64 { + self.budget.spent() + } + + /// Bytes of `ranges`, `(offset, len)` each, that reading them would + /// fetch of a remote file. + pub fn missing_bytes(&self, ranges: &[(u64, u64)]) -> Result { + self.source.missing_bytes(ranges) + } + + /// Takes what `ranges` would fetch from the budget. + fn charge(&self, ranges: &[(u64, u64)]) -> Result<()> { + match self.source.missing_bytes(ranges)? { + 0 => Ok(()), + missing => self.budget.charge(missing), + } + } + + /// Reads bytes of the file within the budget; `once` for bytes a sparse + /// copy need not keep. + fn read(&self, offset: u64, len: u64, once: bool) -> Result> { + if !once { + self.charge(&[(offset, len)])?; + return self.source.read_at(offset, len); + } + // a read that is not kept fetches all of it unless all is held + if self.source.missing_bytes(&[(offset, len)])? > 0 { + self.budget.charge(len)?; + } + self.source.read_once(offset, len) + } + + /// The tensor `name` for a read that decodes its rows, the bytes of a + /// row, and its values. + fn decoded_rows(&self, name: &str) -> Result<(&TensorInfo, u64, usize)> { + let t = self.tensor(name)?; + if t.row_len() > MAX_ROW_VALUES { + return refuse(format!( + "{name} has rows of {} values, more than {MAX_ROW_VALUES}", + t.row_len() + )); + } + Ok((t, t.row_bytes()?, usize::try_from(t.row_len())?)) + } + + pub(crate) fn metadata_str(&self, key: &str) -> Result<&str> { + match self.metadata.get(key) { + Some(MetaValue::Str(value)) => Ok(value), + _ => bail!("claimed GGUF has no string {key}"), + } + } + + /// The tokens the model names that its sampler never picks: the + /// runtime takes them out of every turn's candidates. + pub fn suppressed_tokens(&self) -> &[i32] { + match self.metadata.get(header::SUPPRESSED_TOKENS_KEY) { + Some(MetaValue::Tokens(tokens)) => tokens, + _ => &[], + } + } + + pub fn metadata_f64(&self, key: &str) -> Result { + match self.metadata.get(key) { + Some(MetaValue::Float(value)) => Ok(*value), + _ => bail!("claimed GGUF has no float {key}"), + } + } + + /// All values of a one-dimensional tensor, such as a norm weight, in f64. + pub fn vector(&self, name: &str) -> Result> { + let t = self.tensor(name)?; + if t.dims.len() != 1 { + bail!("{name} is not a vector"); + } + self.row(name, 0) + } + + pub fn tensor(&self, name: &str) -> Result<&TensorInfo> { + self.tensors + .get(name) + .with_context(|| format!("claimed GGUF has no tensor {name}")) + } + + /// Readies `ranges` of the file, `(offset, len)` each, at once. + pub fn prefetch(&self, ranges: &[(u64, u64)]) -> Result<()> { + self.charge(ranges)?; + self.source.prefetch(ranges) + } + + /// The bytes of a tensor, `(offset, len)`. + pub(crate) fn tensor_range(&self, name: &str) -> Result<(u64, u64)> { + let t = self.tensor(name)?; + Ok((t.offset, t.total_bytes()?)) + } + + /// The bytes of row `row` of a weight, `(offset, len)`. + pub fn row_range(&self, name: &str, row: u64) -> Result<(u64, u64)> { + let t = self.tensor(name)?; + if row >= t.row_count()? { + bail!("{name} has no row {row}"); + } + let row_bytes = t.row_bytes()?; + let offset = row + .checked_mul(row_bytes) + .and_then(|at| t.offset.checked_add(at)) + .with_context(|| format!("{name} row {row} is past any offset"))?; + Ok((offset, row_bytes)) + } + + /// Dequantized row `row` of a 2D weight, in f64. + pub fn row(&self, name: &str, row: u64) -> Result> { + let (t, _, n) = self.decoded_rows(name)?; + let (offset, len) = self.row_range(name, row)?; + let raw = self.read(offset, len, false)?; + dequantize_row(t.ggml_type, &raw, n).with_context(|| format!("dequantize {name} row {row}")) + } + + /// Row `row` of a Q4_K or Q5_K weight as its sub-blocks of 32 values. + pub(crate) fn min_blocks(&self, name: &str, row: u64) -> Result> { + let (t, _, _) = self.decoded_rows(name)?; + let (offset, len) = self.row_range(name, row)?; + let raw = self.read(offset, len, false)?; + crate::dequant::min_blocks(t.ggml_type, &raw) + .with_context(|| format!("read {name} row {row}")) + } + + /// Calls `visit` with each of `rows` of a 2D weight, dequantized, in + /// order. Reads many rows at a time. + pub(crate) fn each_row( + &self, + name: &str, + rows: std::ops::Range, + visit: &mut dyn FnMut(u64, &[f64]), + ) -> Result<()> { + self.visit_rows(name, rows, visit, false) + } + + /// [`Self::each_row`] for rows read once: a sparse copy does not keep + /// them. + pub(crate) fn stream_rows( + &self, + name: &str, + rows: std::ops::Range, + visit: &mut dyn FnMut(u64, &[f64]), + ) -> Result<()> { + self.visit_rows(name, rows, visit, true) + } + + fn visit_rows( + &self, + name: &str, + rows: std::ops::Range, + visit: &mut dyn FnMut(u64, &[f64]), + once: bool, + ) -> Result<()> { + /// Bytes read at once. + const CHUNK_BYTES: u64 = 4 << 20; + let (t, row_bytes, n) = self.decoded_rows(name)?; + if rows.end > t.rows() { + bail!("{name} has {} rows, not {}", t.rows(), rows.end); + } + // a row is never empty, so the chunks below are not + let row_size = usize::try_from(row_bytes)?; + let per_chunk = (CHUNK_BYTES / row_bytes).max(1); + let mut first = rows.start; + while first < rows.end { + let count = per_chunk.min(rows.end - first); + let (offset, _) = self.row_range(name, first)?; + let len = count + .checked_mul(row_bytes) + .with_context(|| format!("{name}: {count} rows do not fit a read"))?; + let raw = self.read(offset, len, once)?; + for (i, row) in raw.chunks_exact(row_size).enumerate() { + let index = first + i as u64; + let values = dequantize_row(t.ggml_type, row, n) + .with_context(|| format!("dequantize {name} row {index}"))?; + visit(index, &values); + } + first += count; + } + Ok(()) + } + + /// Weight bytes per layer: an audit opens a layer with this probability. + pub fn layer_bytes(&self) -> BTreeMap { + let mut out = BTreeMap::new(); + for t in self.tensors.values().filter(|t| t.is_matrix()) { + if let Some(layer) = t.layer() { + // a tensor of a file that opened has a size + let bytes = t.total_bytes().unwrap_or(0); + let total: &mut u64 = out.entry(layer).or_insert(0); + *total = total.saturating_add(bytes); + } + } + out + } +} + +/// Checks that the shard at `index` of `count` says it is. +fn check_shard(metadata: &BTreeMap, index: u64, count: u64) -> Result<()> { + let int = |key: &str| match metadata.get(key) { + Some(MetaValue::Int(value)) => Ok(*value), + _ => refuse(format!("its shard {} has no {key}", index + 1)), + }; + if int("split.no")? != index || int("split.count")? != count { + return refuse(format!( + "its shard {} of {count} is not the shard its name says", + index + 1 + )); + } + Ok(()) +} + +/// Small GGUF files in memory, for tests. +#[cfg(test)] +pub(crate) mod test_gguf; + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/weights/header.rs b/crates/skippy-receipts/src/weights/header.rs new file mode 100644 index 00000000..03689d93 --- /dev/null +++ b/crates/skippy-receipts/src/weights/header.rs @@ -0,0 +1,507 @@ +//! The header of a claimed GGUF, read strictly. +//! +//! The node names the model, so every byte of the header may be chosen to +//! break the reader. Each length, count and offset is checked against the +//! [limits](super::limits) and the size of the file before it is used, with +//! arithmetic that cannot wrap. The header must also be one the runtime's +//! own loader takes: little-endian, version 2 or 3, names in UTF-8, each +//! name once, tensors of known types laid end to end at the alignment and +//! inside the file. A header that fails any of this is refused with +//! [`CannotAudit`](super::limits::CannotAudit) before the native loader sees +//! the file. + +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Result, bail}; + +use super::limits::{ + MAX_ARRAY_DEPTH, MAX_DIMS, MAX_HEADER_BYTES, MAX_METADATA_ENTRIES, MAX_NAME_BYTES, + MAX_STRING_BYTES, MAX_TENSORS, refuse, +}; +use super::{ByteSource, MetaValue, TensorInfo}; +use crate::ggml_types::type_layout; + +mod kept_arrays; + +pub use kept_arrays::{MetaArray, TokenList}; + +/// Bytes the first read of a header asks for: one request that holds the +/// header of most models, tokenizer and all. +pub(super) const FIRST_READ: u64 = 8 << 20; +/// The first read of a later shard, whose header has no tokenizer. +pub(super) const SHARD_FIRST_READ: u64 = 1 << 20; + +const GGUF_UINT32: u32 = 4; +const GGUF_INT32: u32 = 5; +const GGUF_FLOAT32: u32 = 6; +const GGUF_BOOL: u32 = 7; +const GGUF_STRING: u32 = 8; +const GGUF_ARRAY: u32 = 9; +const GGUF_FLOAT64: u32 = 12; + +const ALIGNMENT_KEY: &str = "general.alignment"; +/// The tokens the runtime's sampler never picks, whatever a request asks. +pub(crate) const SUPPRESSED_TOKENS_KEY: &str = "tokenizer.ggml.suppress_tokens"; +const DEFAULT_ALIGNMENT: u64 = 32; +/// ggml counts elements in an `int64_t`. +const MAX_ELEMENTS: u64 = i64::MAX as u64; + +pub(super) struct Header { + pub(super) tensors: BTreeMap, + pub(super) metadata: BTreeMap, + /// The arrays a check of the native loader's preconditions reads. + pub(super) arrays: BTreeMap, + /// Where the tensor data starts. + pub(super) data_start: u64, + /// Bytes of the header that were read. + pub(super) header_bytes: u64, +} + +/// Reads the header of the GGUF in `source`, asking for `first_read` bytes +/// first, and refuses a header of more than `max_bytes`: all of +/// [`MAX_HEADER_BYTES`], or what the shards before this one left of it. +pub(super) fn parse_header( + source: &dyn ByteSource, + first_read: u64, + max_bytes: u64, +) -> Result
{ + let mut c = Cursor { + source, + size: source.size(), + buf: Vec::new(), + pos: 0, + first_read: first_read.max(1), + max_bytes: max_bytes.min(MAX_HEADER_BYTES), + }; + if c.bytes(4)? != b"GGUF" { + return refuse("it is not a GGUF file"); + } + check_version(c.u32()?)?; + let n_tensors = c.u64()?; + if n_tensors > MAX_TENSORS { + return refuse(format!( + "its header lists {n_tensors} tensors, more than {MAX_TENSORS}" + )); + } + let n_kv = c.u64()?; + if n_kv > MAX_METADATA_ENTRIES { + return refuse(format!( + "its header holds {n_kv} metadata entries, more than {MAX_METADATA_ENTRIES}" + )); + } + let (metadata, arrays, alignment) = read_metadata(&mut c, n_kv)?; + let listed = (0..n_tensors) + .map(|_| read_tensor(&mut c)) + .collect::>>()?; + let (tensors, data_start) = place_tensors(listed, c.pos as u64, alignment, c.size)?; + Ok(Header { + tensors, + metadata, + arrays, + data_start, + header_bytes: c.pos as u64, + }) +} + +/// The runtime loads little-endian GGUF of versions 2 and 3. +fn check_version(version: u32) -> Result<()> { + match version { + 2 | 3 => Ok(()), + other if matches!(other.swap_bytes(), 1..=3) => { + refuse("it is a big-endian GGUF, which this client does not read") + } + other => refuse(format!( + "it is GGUF version {other}, which this client does not read" + )), + } +} + +/// The bytes of a tensor of `dims` and `ggml_type`, as ggml sizes it. +pub(super) fn tensor_bytes(name: &str, dims: &[u64], ggml_type: u32) -> Result { + let Some((block, block_bytes)) = type_layout(ggml_type) else { + return refuse(format!( + "tensor {name} has ggml type {ggml_type}, which this runtime does not load" + )); + }; + if dims.is_empty() || dims.len() > MAX_DIMS { + return refuse(format!( + "tensor {name} has {} dimensions, not 1 to {MAX_DIMS}", + dims.len() + )); + } + let mut elements = 1u64; + for &dim in dims { + let product = elements + .checked_mul(dim) + .filter(|&product| product > 0 && product <= MAX_ELEMENTS); + let Some(product) = product else { + return refuse(format!( + "tensor {name} has dimensions {dims:?}: one is zero, or their product does not fit" + )); + }; + elements = product; + } + if !dims[0].is_multiple_of(block) { + return refuse(format!( + "tensor {name} has rows of {} values, not whole blocks of {block}", + dims[0] + )); + } + match (elements / block).checked_mul(block_bytes) { + Some(bytes) => Ok(bytes), + None => refuse(format!("tensor {name} has a size that does not fit")), + } +} + +/// A tensor as the header lists it, before the data start is known. +struct Listed { + name: String, + dims: Vec, + ggml_type: u32, + /// Its offset in the tensor data. + relative: u64, + bytes: u64, +} + +/// The scalar metadata, the arrays kept, and the alignment. +type Metadata = ( + BTreeMap, + BTreeMap, + u64, +); + +fn read_metadata(c: &mut Cursor<'_>, count: u64) -> Result { + let mut metadata = BTreeMap::new(); + let mut arrays = BTreeMap::new(); + // arrays are not kept, so the keys seen are more than the metadata's + let mut seen = BTreeSet::new(); + let mut alignment = DEFAULT_ALIGNMENT; + for _ in 0..count { + let key = c.name("a metadata key")?; + let ty = c.u32()?; + let value = if ty == GGUF_ARRAY && key == SUPPRESSED_TOKENS_KEY { + // an array a check reads: the runtime takes these tokens out + // of every candidate list + Some(MetaValue::Tokens(c.token_array()?)) + } else if ty == GGUF_ARRAY { + if let Some(array) = c.kept_array(&key)? { + arrays.insert(key.clone(), array); + } + None + } else { + c.value(ty)? + }; + if key == ALIGNMENT_KEY { + alignment = alignment_of(ty, value.as_ref())?; + } + if !seen.insert(key.clone()) { + return refuse(format!("its header has the metadata key {key} twice")); + } + if let Some(value) = value { + metadata.insert(key, value); + } + } + Ok((metadata, arrays, alignment)) +} + +/// The alignment `general.alignment` gives: a `u32` power of two, as the +/// runtime's loader requires. +fn alignment_of(ty: u32, value: Option<&MetaValue>) -> Result { + match value { + Some(MetaValue::Int(alignment)) if ty == GGUF_UINT32 && alignment.is_power_of_two() => { + Ok(*alignment) + } + _ => refuse(format!("its {ALIGNMENT_KEY} is not a u32 power of two")), + } +} + +fn read_tensor(c: &mut Cursor<'_>) -> Result { + let name = c.name("a tensor name")?; + let rank = c.u32()?; + if rank == 0 || rank as usize > MAX_DIMS { + return refuse(format!( + "tensor {name} has {rank} dimensions, not 1 to {MAX_DIMS}" + )); + } + let dims = (0..rank).map(|_| c.u64()).collect::>>()?; + let ggml_type = c.u32()?; + let relative = c.u64()?; + let bytes = tensor_bytes(&name, &dims, ggml_type)?; + Ok(Listed { + name, + dims, + ggml_type, + relative, + bytes, + }) +} + +/// Gives each tensor its offset in the file. The tensors must lie end to +/// end at the alignment, in the order the header lists them, and inside the +/// file: so the runtime's loader requires, and so no two overlap. +fn place_tensors( + listed: Vec, + header_end: u64, + alignment: u64, + size: u64, +) -> Result<(BTreeMap, u64)> { + let Some(data_start) = header_end.checked_next_multiple_of(alignment) else { + return refuse("its tensor data starts past any offset"); + }; + let mut tensors = BTreeMap::new(); + let mut expected = 0u64; + for tensor in listed { + let name = tensor.name; + if tensor.relative != expected { + return refuse(format!( + "tensor {name} is at offset {} of the tensor data, not at {expected} where the tensor before it ends", + tensor.relative + )); + } + let offset = data_start.checked_add(tensor.relative); + let end = offset + .and_then(|offset| offset.checked_add(tensor.bytes)) + .filter(|&end| end <= size); + let (Some(offset), Some(_)) = (offset, end) else { + return refuse(format!( + "tensor {name} runs past the end of the file ({size} bytes)" + )); + }; + let next = tensor + .bytes + .checked_next_multiple_of(alignment) + .and_then(|padded| expected.checked_add(padded)); + let Some(next) = next else { + return refuse(format!("tensor {name} ends past any offset")); + }; + expected = next; + let info = TensorInfo { + name: name.clone(), + dims: tensor.dims, + ggml_type: tensor.ggml_type, + offset, + }; + if tensors.insert(name.clone(), info).is_some() { + return refuse(format!("its header lists tensor {name} twice")); + } + } + Ok((tensors, data_start)) +} + +/// Bytes of a metadata value of scalar type `ty`. +fn scalar_bytes(ty: u32) -> Option { + match ty { + 0 | 1 | GGUF_BOOL => Some(1), + 2 | 3 => Some(2), + 4..=6 => Some(4), + 10..=12 => Some(8), + _ => None, + } +} + +struct Cursor<'a> { + source: &'a dyn ByteSource, + size: u64, + /// The file from its start, as far as it was read. + buf: Vec, + pos: usize, + first_read: u64, + /// The most bytes the header may take. + max_bytes: u64, +} + +impl Cursor<'_> { + /// The next `n` bytes of the header. + fn bytes(&mut self, n: u64) -> Result<&[u8]> { + let end = (self.pos as u64) + .checked_add(n) + .filter(|&end| end <= self.max_bytes); + let Some(end) = end else { + return refuse(format!( + "its GGUF header, with those of the shards before it, is larger than {MAX_HEADER_BYTES} bytes" + )); + }; + if end > self.size { + return refuse("its GGUF header runs past the end of the file"); + } + self.fill(end)?; + let end = usize::try_from(end)?; + let bytes = &self.buf[self.pos..end]; + self.pos = end; + Ok(bytes) + } + + /// Reads the file up to `end` at least: twice what is held each time, + /// so a header takes few requests of a remote file. + fn fill(&mut self, end: u64) -> Result<()> { + let ceiling = self.size.min(self.max_bytes); + while (self.buf.len() as u64) < end { + let held = self.buf.len() as u64; + let len = held + .max(self.first_read) + .max(end - held) + .min(ceiling - held); + let chunk = self.source.read_at(held, len)?; + if chunk.len() as u64 != len { + bail!( + "read {} bytes of the GGUF header at {held}, not {len}", + chunk.len() + ); + } + self.buf.extend_from_slice(&chunk); + } + Ok(()) + } + + fn skip(&mut self, n: u64) -> Result<()> { + self.bytes(n).map(|_| ()) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.bytes(4)?.try_into()?)) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.bytes(8)?.try_into()?)) + } + + /// A string of at most `max` bytes, which must be UTF-8: a lossy + /// reading would name something the runtime's loader does not. + fn text(&mut self, max: u64, what: &str) -> Result { + let n = self.u64()?; + if n > max { + return refuse(format!( + "{what} of {n} bytes is longer than {max} in its header" + )); + } + match std::str::from_utf8(self.bytes(n)?) { + Ok(text) => Ok(text.to_owned()), + Err(_) => refuse(format!("{what} in its header is not UTF-8")), + } + } + + /// A metadata key or tensor name. + fn name(&mut self, what: &str) -> Result { + let name = self.text(MAX_NAME_BYTES, what)?; + if name.is_empty() || name.chars().any(char::is_control) { + return refuse(format!( + "{what} in its header is empty or holds control characters: {name:?}" + )); + } + Ok(name) + } + + /// Reads a metadata value, returning it when it is a number or a + /// string. Booleans and arrays are skipped. + fn value(&mut self, ty: u32) -> Result> { + if let Some(n) = scalar_bytes(ty) { + let mut le = [0u8; 8]; + le[..n].copy_from_slice(self.bytes(n as u64)?); + return Ok(match ty { + GGUF_FLOAT32 => Some(MetaValue::Float(f64::from(f32::from_le_bytes( + le[..4].try_into()?, + )))), + GGUF_FLOAT64 => Some(MetaValue::Float(f64::from_le_bytes(le))), + GGUF_BOOL => None, + _ => Some(MetaValue::Int(u64::from_le_bytes(le))), + }); + } + match ty { + GGUF_STRING => Ok(Some(MetaValue::Str( + self.text(MAX_STRING_BYTES, "a metadata string")?, + ))), + GGUF_ARRAY => self.skip_array(1).map(|_| None), + other => refuse(format!("its header has the unknown metadata type {other}")), + } + } + + /// An array of `i32` tokens, as the runtime reads the suppressed + /// tokens (`llama_vocab::impl::load` in `src/llama-vocab.cpp`, which + /// refuses an array of any other type). + fn token_array(&mut self) -> Result> { + let inner = self.u32()?; + let count = self.u64()?; + if inner != GGUF_INT32 { + return refuse(format!( + "its {SUPPRESSED_TOKENS_KEY} is an array of type {inner}, not of i32" + )); + } + let Some(bytes) = count.checked_mul(4).filter(|&n| n <= MAX_HEADER_BYTES) else { + return refuse(format!( + "its {SUPPRESSED_TOKENS_KEY} of {count} tokens does not fit a header of {MAX_HEADER_BYTES} bytes" + )); + }; + Ok(self + .bytes(bytes)? + .as_chunks::<4>() + .0 + .iter() + .map(|b| i32::from_le_bytes(*b)) + .collect()) + } + + /// Skips an array at nesting `depth`, 1 for an array that is a value. + /// The recursion ends at [`MAX_ARRAY_DEPTH`], whatever the file says. + /// Returns the number of its elements. + fn skip_array(&mut self, depth: u32) -> Result { + if depth > MAX_ARRAY_DEPTH { + return refuse(format!( + "its metadata arrays nest deeper than {MAX_ARRAY_DEPTH}" + )); + } + let inner = self.u32()?; + let count = self.u64()?; + self.skip_elements(inner, count, depth)?; + Ok(count) + } + + /// Skips the `count` elements of type `inner` of an array at nesting + /// `depth`. + fn skip_elements(&mut self, inner: u32, count: u64, depth: u32) -> Result<()> { + // the fewest bytes an element takes: a string its length, an array + // its type and count + let least = match inner { + GGUF_STRING => 8, + GGUF_ARRAY => 12, + other => match scalar_bytes(other) { + Some(n) => n as u64, + None => { + return refuse(format!( + "its header has an array of the unknown metadata type {other}" + )); + } + }, + }; + let total = count + .checked_mul(least) + .filter(|&total| total <= MAX_HEADER_BYTES); + let Some(total) = total else { + return refuse(format!( + "a metadata array of {count} elements does not fit a header of {MAX_HEADER_BYTES} bytes" + )); + }; + match inner { + GGUF_STRING => { + for _ in 0..count { + let n = self.u64()?; + if n > MAX_STRING_BYTES { + return refuse(format!( + "a metadata string of {n} bytes is longer than {MAX_STRING_BYTES} in its header" + )); + } + self.skip(n)?; + } + } + GGUF_ARRAY => { + for _ in 0..count { + self.skip_array(depth + 1)?; + } + } + _ => self.skip(total)?, + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-receipts/src/weights/header/kept_arrays.rs b/crates/skippy-receipts/src/weights/header/kept_arrays.rs new file mode 100644 index 00000000..b6f3105d --- /dev/null +++ b/crates/skippy-receipts/src/weights/header/kept_arrays.rs @@ -0,0 +1,208 @@ +//! The metadata arrays of a header that a check reads before the native +//! loader sees the file. The header reader skips every other array. +//! +//! The runtime's loader asserts on some of them, which ends the process: +//! two equal strings in `tokenizer.ggml.tokens`, a per-layer expert count +//! above the expert count, rope sections that do not fit a head. So these +//! are read here, and a caller checks them first (the auditor's +//! `native_model::loader_asserts`). + +use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use anyhow::Result; + +use super::super::limits::{MAX_STRING_BYTES, refuse}; +use super::{Cursor, GGUF_STRING, scalar_bytes}; + +/// The vocabulary's tokens, which the loader keeps by text. +pub(crate) const TOKENS_KEY: &str = "tokenizer.ggml.tokens"; +/// The most tokens a vocabulary may hold here. The largest vocabularies +/// of real models have about 262,000. +const MAX_TOKENS: u64 = 1 << 22; +/// The most elements of an integer array that is kept. +const MAX_KEPT_INTS: u64 = 4096; +/// The integer arrays kept, by the end of their key: per-layer counts and +/// rope sections. +const KEPT_INT_SUFFIXES: [&str; 4] = [ + ".expert_used_count", + ".attention.head_count", + ".attention.head_count_kv", + ".rope.dimension_sections", +]; + +/// A metadata array a check of the native loader's preconditions reads. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MetaArray { + /// Integers, signed ones sign-extended. + Ints(Vec), + /// The vocabulary, as the loader reads it ([`TokenList`]). + Tokens(TokenList), +} + +/// What the loader would make of `tokenizer.ggml.tokens`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TokenList { + pub count: u64, + /// The first token whose text an earlier token has, after the loader + /// names an empty token `[EMPTY_i]`: the loader asserts there is none. + pub duplicate: Option, + /// Per byte, a bit set when a token stands for it as a SentencePiece + /// vocabulary looks it up: `<0xXX>`, or the byte alone. + bytes: [u64; 4], +} + +impl TokenList { + /// Whether every byte has a token, which a SentencePiece vocabulary + /// falls back to for text it has no token of. + pub fn has_every_byte(&self) -> bool { + self.bytes.iter().all(|&bits| bits == u64::MAX) + } + + /// Whether a token stands for `byte`. + pub fn has_byte(&self, byte: u8) -> bool { + self.bytes[usize::from(byte >> 6)] >> (byte & 63) & 1 == 1 + } +} + +/// Whether the integer array under `key` is kept. +pub(super) fn keeps_ints(key: &str) -> bool { + KEPT_INT_SUFFIXES.iter().any(|suffix| key.ends_with(suffix)) +} + +/// The byte a token of `text` stands for: `<0xXX>` with upper-case digits, +/// as the loader writes the name, or a text of one byte. +fn byte_of(text: &[u8]) -> Option { + match text { + [byte] => Some(*byte), + [b'<', b'0', b'x', high, low, b'>'] => { + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'A'..=b'F' => Some(d - b'A' + 10), + _ => None, + }; + Some(digit(*high)? << 4 | digit(*low)?) + } + _ => None, + } +} + +fn hash(text: &[u8]) -> u64 { + let mut hasher = DefaultHasher::new(); + text.hash(&mut hasher); + hasher.finish() +} + +impl Cursor<'_> { + /// Reads an array of element type `inner` and `count` elements, after + /// its type and count, as integers; `None`, having skipped it, when its + /// elements are not integers. + pub(super) fn int_array(&mut self, inner: u32, count: u64) -> Result>> { + let signed = matches!(inner, 1 | 3 | 5 | 11); + let Some(width) = scalar_bytes(inner).filter(|_| matches!(inner, 0..=5 | 10 | 11)) else { + self.skip_elements(inner, count, 1)?; + return Ok(None); + }; + if count > MAX_KEPT_INTS { + return refuse(format!( + "its header has an integer array of {count} elements, more than {MAX_KEPT_INTS}" + )); + } + let mut out = Vec::with_capacity(usize::try_from(count)?); + for _ in 0..count { + let bytes = self.bytes(width as u64)?; + let mut le = [0u8; 8]; + le[..width].copy_from_slice(bytes); + let mut value = i64::from_le_bytes(le); + if signed && width < 8 && bytes[width - 1] & 0x80 != 0 { + value |= -1i64 << (width * 8); + } + out.push(value); + } + Ok(Some(out)) + } + + /// Reads `tokenizer.ggml.tokens`, an array of `count` strings after its + /// type and count, as the loader keeps it. Equal texts are found by a + /// hash of each: two equal texts always meet, and two texts that only + /// share a hash refuse a file no loader would. + pub(super) fn token_list(&mut self, count: u64) -> Result { + if count == 0 || count > MAX_TOKENS { + return refuse(format!( + "its vocabulary holds {count} tokens, not 1 to {MAX_TOKENS}" + )); + } + let mut seen = HashSet::with_capacity(usize::try_from(count)?); + let mut list = TokenList { + count, + duplicate: None, + bytes: [0; 4], + }; + for index in 0..count { + let n = self.u64()?; + if n > MAX_STRING_BYTES { + return refuse(format!( + "a token of {n} bytes is longer than {MAX_STRING_BYTES} in its header" + )); + } + let text = self.bytes(n)?; + if let Some(byte) = byte_of(text) { + list.bytes[usize::from(byte >> 6)] |= 1 << (byte & 63); + } + let key = match text.is_empty() { + true => hash(format!("[EMPTY_{index}]").as_bytes()), + false => hash(text), + }; + if !seen.insert(key) && list.duplicate.is_none() { + list.duplicate = Some(index); + } + } + Ok(list) + } + + /// Reads the array under `key`, after its element type and count: kept + /// when a check reads it, else skipped. + pub(super) fn kept_array(&mut self, key: &str) -> Result> { + let inner = self.u32()?; + let count = self.u64()?; + if key == TOKENS_KEY && inner == GGUF_STRING { + return Ok(Some(MetaArray::Tokens(self.token_list(count)?))); + } + if keeps_ints(key) { + return Ok(self.int_array(inner, count)?.map(MetaArray::Ints)); + } + self.skip_elements(inner, count, 1)?; + Ok(None) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_byte_token_is_named_as_the_loader_names_it() { + assert_eq!(byte_of(b"<0x0A>"), Some(10)); + assert_eq!(byte_of(b"<0xFF>"), Some(255)); + assert_eq!(byte_of(b"a"), Some(b'a')); + assert_eq!(byte_of(b"<0xff>"), None); + assert_eq!(byte_of(b"<0x0A"), None); + assert_eq!(byte_of(b"ab"), None); + assert_eq!(byte_of(b""), None); + } + + #[test] + fn only_the_arrays_a_check_reads_are_kept() { + for key in [ + "qwen3moe.expert_used_count", + "llama.attention.head_count", + "llama.attention.head_count_kv", + "qwen35.rope.dimension_sections", + ] { + assert!(keeps_ints(key), "{key}"); + } + assert!(!keeps_ints("tokenizer.ggml.scores")); + assert!(!keeps_ints("tokenizer.ggml.token_type")); + assert!(!keeps_ints("gemma4.attention.sliding_window_pattern")); + } +} diff --git a/crates/skippy-receipts/src/weights/header/tests.rs b/crates/skippy-receipts/src/weights/header/tests.rs new file mode 100644 index 00000000..9759c5a2 --- /dev/null +++ b/crates/skippy-receipts/src/weights/header/tests.rs @@ -0,0 +1,668 @@ +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::super::limits::CannotAudit; +use super::super::test_gguf::{Memory, string}; +use super::*; +use crate::ggml_types::{GGML_F32, GGML_Q4_K, GGML_Q8_0}; + +const UINT8: u32 = 0; +const UINT64: u32 = 10; + +/// A GGUF written field by field, so a test can write what no writer would. +struct Raw(Vec); + +impl Raw { + fn new(version: u32, tensors: u64, entries: u64) -> Self { + let mut out = b"GGUF".to_vec(); + out.extend(version.to_le_bytes()); + out.extend(tensors.to_le_bytes()); + out.extend(entries.to_le_bytes()); + Self(out) + } + + fn u32(mut self, value: u32) -> Self { + self.0.extend(value.to_le_bytes()); + self + } + + fn u64(mut self, value: u64) -> Self { + self.0.extend(value.to_le_bytes()); + self + } + + fn bytes(mut self, bytes: &[u8]) -> Self { + self.0.extend(bytes); + self + } + + fn text(mut self, text: &str) -> Self { + string(&mut self.0, text); + self + } + + /// A metadata key and the type of its value. + fn key(self, key: &str, ty: u32) -> Self { + self.text(key).u32(ty) + } + + /// The type and count that start an array. + fn array(self, inner: u32, count: u64) -> Self { + self.u32(inner).u64(count) + } + + fn tensor(mut self, name: &str, dims: &[u64], ggml_type: u32, relative: u64) -> Self { + string(&mut self.0, name); + self.0.extend((dims.len() as u32).to_le_bytes()); + for dim in dims { + self.0.extend(dim.to_le_bytes()); + } + self.u32(ggml_type).u64(relative) + } + + /// Pads to the alignment and adds `data` bytes of tensor data. + fn data(mut self, alignment: usize, data: usize) -> Vec { + let start = self.0.len().div_ceil(alignment) * alignment; + self.0.resize(start + data, 0); + self.0 + } +} + +fn parse(bytes: Vec) -> Result
{ + parse_header(&Memory(bytes), FIRST_READ, MAX_HEADER_BYTES) +} + +/// The reason a header is refused: always a [`CannotAudit`], never a panic +/// and never another error. +fn refused(bytes: Vec) -> String { + let error = parse(bytes).err().expect("the header is refused"); + assert!(CannotAudit::caused(&error), "{error:#}"); + error.to_string() +} + +/// One f32 matrix `w` of two rows of four values. +fn one_tensor(entries: u64) -> Raw { + Raw::new(3, 1, entries) +} + +fn with_w(raw: Raw) -> Vec { + raw.tensor("w", &[4, 2], GGML_F32, 0).data(32, 32) +} + +#[test] +fn a_header_reads_its_metadata_and_places_its_tensors() { + let bytes = Raw::new(3, 2, 6) + .key("general.architecture", GGUF_STRING) + .text("toy") + .key("toy.block_count", GGUF_UINT32) + .u32(7) + .key("toy.eps", GGUF_FLOAT32) + .bytes(&0.5f32.to_le_bytes()) + .key("toy.flag", GGUF_BOOL) + .bytes(&[1]) + // an array of strings, and an array of arrays + .key("tokenizer.tokens", GGUF_ARRAY) + .array(GGUF_STRING, 2) + .text("a") + .bytes(&3u64.to_le_bytes()) + .bytes(&[0xff, 0xfe, 0xfd]) + .key("toy.nested", GGUF_ARRAY) + .array(GGUF_ARRAY, 2) + .array(UINT8, 3) + .bytes(&[1, 2, 3]) + .array(GGUF_STRING, 1) + .text("deep") + .tensor("blk.0.w", &[4, 2], GGML_F32, 0) + .tensor("blk.0.q", &[32, 3], GGML_Q8_0, 32) + .data(32, 32 + 102); + let size = bytes.len() as u64; + let header = parse(bytes).unwrap(); + assert_eq!( + header.metadata.get("general.architecture"), + Some(&MetaValue::Str("toy".into())) + ); + assert_eq!( + header.metadata.get("toy.block_count"), + Some(&MetaValue::Int(7)) + ); + assert_eq!(header.metadata.get("toy.eps"), Some(&MetaValue::Float(0.5))); + assert_eq!(header.metadata.len(), 3); + assert_eq!(header.data_start % 32, 0); + let w = &header.tensors["blk.0.w"]; + assert_eq!( + (w.offset, w.total_bytes().unwrap()), + (header.data_start, 32) + ); + let q = &header.tensors["blk.0.q"]; + assert_eq!(q.offset, header.data_start + 32); + assert_eq!(q.offset + q.total_bytes().unwrap(), size); +} + +#[test] +fn arrays_nested_too_deep_are_refused_without_recursion() { + let nested = |levels: usize| { + let mut raw = one_tensor(1).key("deep", GGUF_ARRAY); + for _ in 1..levels { + raw = raw.array(GGUF_ARRAY, 1); + } + with_w(raw.array(UINT8, 1).bytes(&[0])) + }; + assert!(parse(nested(1)).is_ok()); + assert!(parse(nested(2)).is_ok()); + assert!(refused(nested(3)).contains("nest deeper")); + // as many levels as a megabyte holds: once a frame of the stack each + assert!(refused(nested(80_000)).contains("nest deeper")); +} + +#[test] +fn lengths_and_counts_past_the_limits_are_refused() { + let cases: Vec<(&str, Vec)> = vec![ + ("tensors", Raw::new(3, MAX_TENSORS + 1, 0).data(32, 0)), + ("tensors", Raw::new(3, u64::MAX, 0).data(32, 0)), + ( + "metadata entries", + Raw::new(3, 0, MAX_METADATA_ENTRIES + 1).data(32, 0), + ), + ("metadata entries", Raw::new(3, 0, u64::MAX).data(32, 0)), + // a key length that wraps the cursor + ("longer than", one_tensor(1).u64(u64::MAX - 7).data(32, 0)), + ( + "longer than", + one_tensor(1).u64(MAX_NAME_BYTES + 1).data(32, 0), + ), + ( + "longer than", + one_tensor(1) + .key("k", GGUF_STRING) + .u64(MAX_STRING_BYTES + 1) + .data(32, 0), + ), + ( + "longer than", + one_tensor(1) + .key("k", GGUF_ARRAY) + .array(GGUF_STRING, 1) + .u64(u64::MAX) + .data(32, 0), + ), + ( + "does not fit", + one_tensor(1) + .key("k", GGUF_ARRAY) + .array(UINT64, u64::MAX / 4) + .data(32, 0), + ), + ( + "does not fit", + one_tensor(1) + .key("k", GGUF_ARRAY) + .array(GGUF_STRING, u64::MAX) + .data(32, 0), + ), + ( + "does not fit", + one_tensor(1) + .key("k", GGUF_ARRAY) + .array(GGUF_ARRAY, 1 << 40) + .data(32, 0), + ), + ( + "longer than", + Raw::new(3, 1, 0).u64(MAX_NAME_BYTES + 1).data(32, 0), + ), + ]; + for (reason, bytes) in cases { + let refused = refused(bytes); + assert!(refused.contains(reason), "{reason}: {refused}"); + } +} + +/// A file of `size` bytes whose start is `held` and whose rest is zeros, +/// which counts what is read of it. +struct Counted { + held: Vec, + size: u64, + requests: AtomicU64, + read: AtomicU64, +} + +impl Counted { + fn new(held: Vec, size: u64) -> Self { + Self { + held, + size, + requests: AtomicU64::new(0), + read: AtomicU64::new(0), + } + } +} + +impl ByteSource for Counted { + fn read_at(&self, offset: u64, len: u64) -> Result> { + assert!(len <= 64 << 20, "a read of {len} bytes"); + assert!(offset + len <= self.size); + self.requests.fetch_add(1, Ordering::SeqCst); + self.read.fetch_add(len, Ordering::SeqCst); + let mut out = vec![0u8; len as usize]; + if let Some(held) = self.held.get(offset as usize..) { + let n = held.len().min(out.len()); + out[..n].copy_from_slice(&held[..n]); + } + Ok(out) + } + + fn size(&self) -> u64 { + self.size + } +} + +#[test] +fn a_length_that_asks_for_the_file_reads_none_of_it() { + // a remote file of a terabyte whose header says an array is all of it + let size = 1u64 << 40; + let start = one_tensor(1) + .key("k", GGUF_ARRAY) + .array(UINT8, size - 100) + .data(32, 0); + let source = Counted::new(start, size); + let error = parse_header(&source, FIRST_READ, MAX_HEADER_BYTES) + .err() + .unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + // an array that fits the count check and not the header + let start = one_tensor(1) + .key("k", GGUF_ARRAY) + .array(UINT8, MAX_HEADER_BYTES - 16) + .data(32, 0); + let fits = Counted::new(start, size); + let error = parse_header(&fits, FIRST_READ, MAX_HEADER_BYTES) + .err() + .unwrap(); + assert!(error.to_string().contains("larger than"), "{error:#}"); + for source in [source, fits] { + assert_eq!(source.requests.load(Ordering::SeqCst), 1); + assert_eq!(source.read.load(Ordering::SeqCst), FIRST_READ); + } +} + +#[test] +fn a_header_takes_one_request_and_grows_by_doubling() { + // a tokenizer of three megabytes: one request, where a megabyte at a + // time and doubling took three + let tokens = vec![b'x'; 3 << 20]; + let small = with_w( + one_tensor(1) + .key("tokens", GGUF_ARRAY) + .array(UINT8, tokens.len() as u64) + .bytes(&tokens), + ); + let size = small.len() as u64; + let source = Counted::new(small, size); + parse_header(&source, FIRST_READ, MAX_HEADER_BYTES).unwrap(); + assert_eq!(source.requests.load(Ordering::SeqCst), 1); + // twenty megabytes: the first 8, what the array then needs, and as + // much again, which is the rest + let tokens = vec![b'x'; 20 << 20]; + let large = with_w( + one_tensor(1) + .key("tokens", GGUF_ARRAY) + .array(UINT8, tokens.len() as u64) + .bytes(&tokens), + ); + let size = large.len() as u64; + let source = Counted::new(large, size); + parse_header(&source, FIRST_READ, MAX_HEADER_BYTES).unwrap(); + assert_eq!(source.requests.load(Ordering::SeqCst), 3); + assert_eq!(source.read.load(Ordering::SeqCst), size); + // a later shard asks for less first + let shard = Counted::new(with_w(one_tensor(0)), 4 << 20); + parse_header(&shard, SHARD_FIRST_READ, MAX_HEADER_BYTES).unwrap(); + assert_eq!(shard.read.load(Ordering::SeqCst), SHARD_FIRST_READ); +} + +#[test] +fn a_shard_reads_only_what_the_shards_before_it_left_of_the_limit() { + let bytes = with_w(one_tensor(0)); + let header = parse(bytes.clone()).unwrap(); + assert!(header.header_bytes <= header.data_start); + let left = |max_bytes: u64| { + let source = Counted::new(bytes.clone(), 4 << 20); + let parsed = parse_header(&source, SHARD_FIRST_READ, max_bytes); + (parsed, source.read.load(Ordering::SeqCst)) + }; + let (parsed, read) = left(header.header_bytes); + assert!(parsed.is_ok()); + assert_eq!(read, header.header_bytes); + for max_bytes in [header.header_bytes - 1, 8, 0] { + let (parsed, read) = left(max_bytes); + let error = parsed.err().unwrap(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(error.to_string().contains("larger than"), "{error}"); + assert!(read <= max_bytes); + } +} + +#[test] +fn versions_and_byte_orders_the_runtime_does_not_load_are_refused() { + assert!(parse(with_w(Raw::new(2, 1, 0))).is_ok()); + assert!(parse(with_w(Raw::new(3, 1, 0))).is_ok()); + for version in [0, 1, 4, 0x0001_0000, u32::MAX] { + let refused = refused(with_w(Raw::new(version, 1, 0))); + assert!(refused.contains("version"), "{version}: {refused}"); + } + // version 3 and 2 as a big-endian writer writes them + for version in [3u32, 2] { + let refused = refused(with_w(Raw::new(version.swap_bytes(), 1, 0))); + assert!(refused.contains("big-endian"), "{refused}"); + } + let mut not_gguf = with_w(Raw::new(3, 1, 0)); + not_gguf[..4].copy_from_slice(b"GGML"); + assert!(refused(not_gguf).contains("not a GGUF")); + // a hole of a sparse copy + assert!(refused(vec![0u8; 4096]).contains("not a GGUF")); + assert!(refused(Vec::new()).contains("past the end")); +} + +#[test] +fn names_the_loader_would_read_otherwise_are_refused() { + let bad_utf8 = [0x62, 0x6c, 0x6b, 0xff]; + let named = |name: &[u8]| { + Raw::new(3, 1, 0) + .u64(name.len() as u64) + .bytes(name) + .u32(2) + .u64(4) + .u64(2) + .u32(GGML_F32) + .u64(0) + .data(32, 32) + }; + assert!(parse(named(b"blk.0.w")).is_ok()); + assert!(refused(named(&bad_utf8)).contains("not UTF-8")); + assert!(refused(named(b"")).contains("empty")); + assert!(refused(named(b"blk.0\0.w")).contains("control")); + assert!(refused(named(b"blk.0\n.w")).contains("control")); + let keyed = |key: &[u8]| { + with_w( + one_tensor(1) + .u64(key.len() as u64) + .bytes(key) + .u32(GGUF_UINT32) + .u32(1), + ) + }; + assert!(parse(keyed(b"general.x")).is_ok()); + assert!(refused(keyed(&bad_utf8)).contains("not UTF-8")); + assert!(refused(keyed(b"")).contains("empty")); + assert!(refused(keyed(b"a\x1bb")).contains("control")); + let valued = with_w( + one_tensor(1) + .key("general.name", GGUF_STRING) + .u64(4) + .bytes(&bad_utf8), + ); + assert!(refused(valued).contains("not UTF-8")); +} + +#[test] +fn names_that_come_twice_are_refused() { + let keys = with_w( + one_tensor(2) + .key("general.x", GGUF_UINT32) + .u32(1) + .key("general.x", GGUF_UINT32) + .u32(2), + ); + assert!(refused(keys).contains("twice")); + // an array is not kept, and its key still counts + let array_key = with_w( + one_tensor(2) + .key("general.x", GGUF_ARRAY) + .array(UINT8, 0) + .key("general.x", GGUF_UINT32) + .u32(2), + ); + assert!(refused(array_key).contains("twice")); + let tensors = Raw::new(3, 2, 0) + .tensor("w", &[4, 2], GGML_F32, 0) + .tensor("w", &[4, 2], GGML_F32, 32) + .data(32, 64); + assert!(refused(tensors).contains("twice")); +} + +#[test] +fn metadata_of_unknown_types_and_bad_alignments_are_refused() { + let typed = |ty: u32| with_w(one_tensor(1).key("k", ty).u64(0)); + for ty in [13, 14, 255, u32::MAX] { + assert!(refused(typed(ty)).contains("unknown metadata type")); + let array = with_w(one_tensor(1).key("k", GGUF_ARRAY).array(ty, 1).u64(0)); + assert!(refused(array).contains("unknown metadata type")); + } + let aligned = |ty: u32, value: &[u8], alignment: usize| { + one_tensor(1) + .key(ALIGNMENT_KEY, ty) + .bytes(value) + .tensor("w", &[4, 2], GGML_F32, 0) + .data(alignment, 32) + }; + let header = parse(aligned(GGUF_UINT32, &64u32.to_le_bytes(), 64)).unwrap(); + assert_eq!(header.data_start % 64, 0); + for alignment in [0u32, 3, 48, u32::MAX] { + let bytes = aligned(GGUF_UINT32, &alignment.to_le_bytes(), 32); + assert!(refused(bytes).contains("power of two"), "{alignment}"); + } + // the loader takes a u32 only: another type would abort it + let u64_typed = aligned(UINT64, &32u64.to_le_bytes(), 32); + assert!(refused(u64_typed).contains("power of two")); + let string_typed = with_w(one_tensor(1).key(ALIGNMENT_KEY, GGUF_STRING).text("32")); + assert!(refused(string_typed).contains("power of two")); +} + +#[test] +fn tensors_of_bad_shapes_and_types_are_refused() { + let shaped = |dims: &[u64], ggml_type: u32| { + Raw::new(3, 1, 0) + .tensor("w", dims, ggml_type, 0) + .data(32, 64) + }; + assert!(parse(shaped(&[4, 2, 1, 1], GGML_F32)).is_ok()); + assert!(parse(shaped(&[32, 1], GGML_Q8_0)).is_ok()); + let cases: Vec<(&str, Vec)> = vec![ + ("dimensions", shaped(&[], GGML_F32)), + ("dimensions", shaped(&[1, 1, 1, 1, 1], GGML_F32)), + // a rank that would read the rest of the file as dimensions + ( + "dimensions", + Raw::new(3, 1, 0) + .text("w") + .u32(u32::MAX) + .u64(4) + .data(32, 64), + ), + ("zero", shaped(&[0], GGML_F32)), + ("zero", shaped(&[4, 0], GGML_F32)), + ("does not fit", shaped(&[1 << 32, 1 << 32], GGML_F32)), + ("does not fit", shaped(&[u64::MAX, 2], GGML_F32)), + ("does not fit", shaped(&[1 << 62, 2], GGML_F32)), + ("does not fit", shaped(&[1 << 62], GGML_F32)), + // a row shorter than a block, which has no bytes + ("whole blocks", shaped(&[16, 2], GGML_Q8_0)), + ("whole blocks", shaped(&[255, 2], GGML_Q4_K)), + ("whole blocks", shaped(&[33, 2], GGML_Q8_0)), + ("does not load", shaped(&[4, 2], 4)), + ("does not load", shaped(&[4, 2], 5)), + ("does not load", shaped(&[4, 2], 31)), + ("does not load", shaped(&[4, 2], 44)), + ("does not load", shaped(&[4, 2], u32::MAX)), + ]; + for (reason, bytes) in cases { + let refused = refused(bytes); + assert!(refused.contains(reason), "{reason}: {refused}"); + } +} + +#[test] +fn tensors_out_of_place_are_refused() { + let two = |second: u64, data: usize| { + Raw::new(3, 2, 0) + .tensor("a", &[4, 2], GGML_F32, 0) + .tensor("b", &[4, 2], GGML_F32, second) + .data(32, data) + }; + assert!(parse(two(32, 64)).is_ok()); + // on the first, off the alignment, after a gap, and wrapped + for second in [0, 16, 31, 33, 64, u64::MAX, u64::MAX - 31] { + let refused = refused(two(second, 4096)); + assert!( + refused.contains("where the tensor before it ends"), + "{second}" + ); + } + // the last tensor ends past the file + for data in [0, 32, 63] { + assert!(refused(two(32, data)).contains("past the end"), "{data}"); + } + let first_misplaced = Raw::new(3, 1, 0) + .tensor("a", &[4, 2], GGML_F32, 32) + .data(32, 4096); + assert!(refused(first_misplaced).contains("not at 0")); + // a tensor as large as ggml counts, in a file that is not + let huge = Raw::new(3, 1, 0) + .tensor("a", &[1 << 60], GGML_F32, 0) + .data(32, 64); + assert!(refused(huge).contains("past the end")); +} + +#[test] +fn a_header_cut_anywhere_is_refused() { + let whole = Raw::new(3, 2, 3) + .key("general.architecture", GGUF_STRING) + .text("toy") + .key("toy.list", GGUF_ARRAY) + .array(GGUF_STRING, 2) + .text("a") + .text("b") + .key("toy.n", GGUF_UINT32) + .u32(7) + .tensor("a", &[4, 2], GGML_F32, 0) + .tensor("b", &[32, 1], GGML_Q8_0, 32) + .data(32, 32 + 34); + assert!(parse(whole.clone()).is_ok()); + for cut in 0..whole.len() { + refused(whole[..cut].to_vec()); + } +} + +#[test] +fn any_byte_changed_is_parsed_or_refused_and_never_panics() { + let whole = Raw::new(3, 2, 3) + .key("general.architecture", GGUF_STRING) + .text("toy") + .key("toy.list", GGUF_ARRAY) + .array(GGUF_ARRAY, 1) + .array(UINT8, 2) + .bytes(&[1, 2]) + .key(ALIGNMENT_KEY, GGUF_UINT32) + .u32(32) + .tensor("a", &[4, 2], GGML_F32, 0) + .tensor("b", &[32, 1], GGML_Q8_0, 32) + .data(32, 32 + 34); + let header_end = whole.len() - (32 + 34); + for at in 0..header_end { + for value in [0x00, 0x01, 0x7f, 0x80, 0xff] { + let mut changed = whole.clone(); + if changed[at] == value { + continue; + } + changed[at] = value; + if let Err(error) = parse(changed) { + assert!( + CannotAudit::caused(&error), + "byte {at} to {value}: {error:#}" + ); + } + } + } +} + +#[test] +fn the_list_of_suppressed_tokens_is_kept() { + const INT32: u32 = 5; + let with = |key: &str, count: u64| { + let mut raw = one_tensor(1).key(key, GGUF_ARRAY).array(INT32, count); + for token in 0..count { + raw = raw.bytes(&(token as i32).to_le_bytes()); + } + parse(with_w(raw)).unwrap() + }; + let header = with(SUPPRESSED_TOKENS_KEY, 3); + assert_eq!( + header.metadata.get(SUPPRESSED_TOKENS_KEY), + Some(&MetaValue::Tokens(vec![0, 1, 2])) + ); + // an empty list, and any other array, as before + assert_eq!( + with(SUPPRESSED_TOKENS_KEY, 0) + .metadata + .get(SUPPRESSED_TOKENS_KEY), + Some(&MetaValue::Tokens(Vec::new())) + ); + assert!(with("tokenizer.ggml.token_type", 3).metadata.is_empty()); + // the runtime refuses a list of another type, and so does the check + let strings = one_tensor(1) + .key(SUPPRESSED_TOKENS_KEY, GGUF_ARRAY) + .array(4, 1) + .bytes(&7u32.to_le_bytes()); + assert!(parse(with_w(strings)).is_err()); +} + +const INT32: u32 = 5; + +/// A header whose only entries are `tokenizer.ggml.tokens` holding +/// `tokens` and `toy.expert_used_count` holding `used`. +fn with_arrays(tokens: &[&[u8]], used: &[i32]) -> Vec { + let mut raw = one_tensor(2) + .key(kept_arrays::TOKENS_KEY, GGUF_ARRAY) + .array(GGUF_STRING, tokens.len() as u64); + for token in tokens { + raw = raw.u64(token.len() as u64).bytes(token); + } + raw = raw + .key("toy.expert_used_count", GGUF_ARRAY) + .array(INT32, used.len() as u64); + for value in used { + raw = raw.bytes(&value.to_le_bytes()); + } + with_w(raw) +} + +#[test] +fn the_arrays_the_loader_asserts_on_are_kept() { + let header = parse(with_arrays(&[b"a", b"<0x0A>", b"", b"b"], &[2, -1])).unwrap(); + let Some(MetaArray::Tokens(tokens)) = header.arrays.get(kept_arrays::TOKENS_KEY) else { + panic!("{:?}", header.arrays); + }; + assert_eq!(tokens.count, 4); + assert_eq!(tokens.duplicate, None); + assert!(tokens.has_byte(10) && tokens.has_byte(b'a') && !tokens.has_byte(0)); + assert!(!tokens.has_every_byte()); + assert_eq!( + header.arrays.get("toy.expert_used_count"), + Some(&MetaArray::Ints(vec![2, -1])) + ); +} + +#[test] +fn two_tokens_of_one_text_are_found() { + let twice = parse(with_arrays(&[b"a", b"b", b"a"], &[])).unwrap(); + let Some(MetaArray::Tokens(tokens)) = twice.arrays.get(kept_arrays::TOKENS_KEY) else { + panic!("no tokens"); + }; + assert_eq!(tokens.duplicate, Some(2)); + // the loader names an empty token by its index, which another may have + let renamed = parse(with_arrays(&[b"[EMPTY_1]", b""], &[])).unwrap(); + let Some(MetaArray::Tokens(tokens)) = renamed.arrays.get(kept_arrays::TOKENS_KEY) else { + panic!("no tokens"); + }; + assert_eq!(tokens.duplicate, Some(1)); + assert!(refused(with_arrays(&[], &[])).contains("tokens")); +} diff --git a/crates/skippy-receipts/src/weights/limits.rs b/crates/skippy-receipts/src/weights/limits.rs new file mode 100644 index 00000000..cb9b85cd --- /dev/null +++ b/crates/skippy-receipts/src/weights/limits.rs @@ -0,0 +1,191 @@ +//! What this client refuses to read of a claimed GGUF, and the error that +//! says so. +//! +//! The node that issued a receipt names the model, so the header, the +//! tensors and the sizes an audit reads are whatever that node chose to +//! publish. Every count, length and size of the file is checked against a +//! limit here before the client allocates or fetches for it. A limit that +//! trips means this client cannot audit the model. It is never a verdict on +//! the node: [`CannotAudit`] is the error for it. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use anyhow::Result; + +/// The largest GGUF header, up to the first tensor's data, that is read. +/// Headers of real models are 8 to 16 MiB with the tokenizer. +pub(crate) const MAX_HEADER_BYTES: u64 = 256 << 20; +/// The most tensors a header may list. +pub(crate) const MAX_TENSORS: u64 = 1 << 16; +/// The most metadata entries a header may hold. +pub(crate) const MAX_METADATA_ENTRIES: u64 = 1 << 16; +/// The longest metadata key or tensor name, in bytes. +pub(crate) const MAX_NAME_BYTES: u64 = 1024; +/// The longest metadata string, in bytes. +pub(crate) const MAX_STRING_BYTES: u64 = 64 << 20; +/// How deep metadata arrays may nest: an array of arrays, and no deeper. +pub(crate) const MAX_ARRAY_DEPTH: u32 = 2; +/// The most dimensions of a tensor, as ggml has them. +pub(crate) const MAX_DIMS: usize = 4; +/// The most shards of a split GGUF. +pub(crate) const MAX_SHARDS: usize = 128; +/// The most values of one weight row that is read and decoded. +pub(crate) const MAX_ROW_VALUES: u64 = 1 << 24; +/// The largest tensor outside the layers that a sparse copy fetches whole. +pub(crate) const WHOLE_TENSOR_LIMIT: u64 = 256 << 20; +/// Bytes one audit fetches of a remote claimed GGUF before it refuses: what +/// an audit of the largest model the auditor was measured on reads, with +/// headroom. A caller opens a remote file with it, or with a budget of its +/// own ([`WeightFile::open_with_budget`]). +/// +/// The model is Qwen3.5-397B-A17B: its output matrix, 248,320 rows of +/// 4,096 values, is the largest of the measured models. An audit reads, at +/// most: +/// +/// - the output matrix once, streamed for a new head key: 1.89 GiB in +/// bf16 or f16 (1.01 GiB in q8_0, 0.78 GiB in q6_K, as the quantized +/// files ship it); +/// - the header, which counts against the first audit of an opened file: +/// 12 MiB measured, and at most [`MAX_HEADER_BYTES`]; +/// - the tensors a challenged layer loads whole and the rows the checks +/// read: 10 to 14 MiB measured, of which the four expert routers, read +/// whole, are 8 MiB each. +/// +/// That is 1.9 GiB with a 16-bit output matrix and the header at its +/// limit. The budget leaves about a half of that again. A file whose output +/// matrix is f32 at that size is refused, as no audit. +/// +/// [`WeightFile::open_with_budget`]: crate::weights::WeightFile::open_with_budget +pub const AUDIT_FETCH_BUDGET: u64 = 3 << 30; + +/// A claimed GGUF this client will not read: over a limit of this client, +/// or not a GGUF the runtime loads. It says nothing about the node. +#[derive(Debug)] +pub struct CannotAudit(String); + +impl CannotAudit { + pub fn new(reason: impl Into) -> Self { + Self(reason.into()) + } + + /// Whether `error` is, or was caused by, a refusal of this kind. + pub fn caused(error: &anyhow::Error) -> bool { + error.chain().any(|cause| cause.is::()) + } +} + +impl fmt::Display for CannotAudit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "this client cannot audit this model: {}; that is not a verdict on the node", + self.0 + ) + } +} + +impl std::error::Error for CannotAudit {} + +/// Refuses the claimed GGUF for `reason`. +pub fn refuse(reason: impl Into) -> Result { + Err(CannotAudit::new(reason).into()) +} + +/// How many bytes a [`WeightFile`] may still fetch from a remote file. +/// +/// [`WeightFile`]: crate::weights::WeightFile +#[derive(Debug)] +pub(crate) struct FetchBudget { + limit: AtomicU64, + spent: AtomicU64, + /// What was spent since the file opened, its header, is the first + /// audit's to count: the first [`Self::reset`] keeps it. + opened: AtomicBool, +} + +impl FetchBudget { + /// A budget of `limit` bytes for a file being opened. + pub fn new(limit: u64) -> Self { + Self { + limit: AtomicU64::new(limit), + spent: AtomicU64::new(0), + opened: AtomicBool::new(true), + } + } + + /// Starts over with a budget of `limit` bytes. + pub fn set(&self, limit: u64) { + self.limit.store(limit, Ordering::SeqCst); + self.spent.store(0, Ordering::SeqCst); + self.opened.store(false, Ordering::SeqCst); + } + + /// Starts over with the same budget, for the next audit. The first + /// audit after the file opened keeps what the open fetched. + pub fn reset(&self) { + if !self.opened.swap(false, Ordering::SeqCst) { + self.spent.store(0, Ordering::SeqCst); + } + } + + pub fn limit(&self) -> u64 { + self.limit.load(Ordering::SeqCst) + } + + pub fn spent(&self) -> u64 { + self.spent.load(Ordering::SeqCst) + } + + /// Takes `bytes` from the budget, or refuses when it does not hold them. + pub fn charge(&self, bytes: u64) -> Result<()> { + let limit = self.limit(); + let charged = self + .spent + .try_update(Ordering::SeqCst, Ordering::SeqCst, |spent| { + spent.checked_add(bytes).filter(|&total| total <= limit) + }); + match charged { + Ok(_) => Ok(()), + Err(spent) => refuse(format!( + "the audit would fetch {bytes} more bytes of it after {spent}, past the budget of {limit} bytes" + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_budget_refuses_what_it_does_not_hold() { + let budget = FetchBudget::new(100); + // what the open fetched counts against the first audit + budget.charge(10).unwrap(); + budget.reset(); + assert_eq!(budget.spent(), 10); + budget.reset(); + assert_eq!(budget.spent(), 0); + budget.charge(60).unwrap(); + let refused = budget.charge(41).unwrap_err(); + assert!(CannotAudit::caused(&refused), "{refused:#}"); + assert!(refused.to_string().contains("not a verdict on the node")); + // what was refused is not spent + budget.charge(40).unwrap(); + assert!(budget.charge(1).is_err()); + assert!(budget.charge(u64::MAX).is_err()); + budget.reset(); + budget.charge(100).unwrap(); + budget.set(10); + assert_eq!((budget.limit(), budget.spent()), (10, 0)); + assert!(budget.charge(11).is_err()); + } + + #[test] + fn a_refusal_is_found_under_context() { + let refused = refuse::<()>("too large").unwrap_err().context("open it"); + assert!(CannotAudit::caused(&refused)); + assert!(!CannotAudit::caused(&anyhow::anyhow!("the network failed"))); + } +} diff --git a/crates/skippy-receipts/src/weights/test_gguf.rs b/crates/skippy-receipts/src/weights/test_gguf.rs new file mode 100644 index 00000000..226d99fa --- /dev/null +++ b/crates/skippy-receipts/src/weights/test_gguf.rs @@ -0,0 +1,173 @@ +//! Small GGUF files in memory, for tests. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{Context, Result, bail}; + +use super::{ByteSource, MetaValue, WeightFile}; +use crate::ggml_types::{GGML_F32, type_layout}; + +pub(crate) struct Memory(pub(crate) Vec); + +impl ByteSource for Memory { + fn read_at(&self, offset: u64, len: u64) -> Result> { + let start = usize::try_from(offset)?; + let end = start + .checked_add(usize::try_from(len)?) + .context("read past the end")?; + self.0 + .get(start..end) + .map(<[u8]>::to_vec) + .context("read past the end") + } + + fn size(&self) -> u64 { + self.0.len() as u64 + } +} + +/// A remote file of `size` bytes as a reader of its sparse copy sees it: +/// the `held` bytes at its start are here, and every byte past them is +/// fetched, and reads as zero. +pub(crate) struct Remote { + pub(crate) held: Vec, + pub(crate) size: u64, + /// Bytes read past the held ones. + pub(crate) fetched: AtomicU64, +} + +impl Remote { + pub(crate) fn new(held: Vec, size: u64) -> Self { + Self { + held, + size, + fetched: AtomicU64::new(0), + } + } + + /// The bytes of `[offset, offset + len)` past the held ones. + fn past_held(&self, offset: u64, len: u64) -> Result { + let end = offset.checked_add(len).filter(|&end| end <= self.size); + let end = end.context("read past the end")?; + Ok(end.saturating_sub(offset.max(self.held.len() as u64))) + } +} + +impl ByteSource for Remote { + fn read_at(&self, offset: u64, len: u64) -> Result> { + let fetched = self.past_held(offset, len)?; + if len > 64 << 20 { + bail!("a test reads at most 64 MiB at once, not {len} bytes"); + } + self.fetched.fetch_add(fetched, Ordering::SeqCst); + let mut out = vec![0u8; len as usize]; + let start = offset as usize; + if let Some(held) = self.held.get(start..) { + let n = held.len().min(out.len()); + out[..n].copy_from_slice(&held[..n]); + } + Ok(out) + } + + fn size(&self) -> u64 { + self.size + } + + fn missing_bytes(&self, ranges: &[(u64, u64)]) -> Result { + ranges.iter().try_fold(0u64, |sum, &(offset, len)| { + Ok(sum + self.past_held(offset, len)?) + }) + } +} + +pub(crate) fn string(out: &mut Vec, s: &str) { + out.extend((s.len() as u64).to_le_bytes()); + out.extend(s.as_bytes()); +} + +/// A GGUF with `metadata` and f32 `tensors` (name, dims, values). +pub(crate) fn open( + metadata: &[(&str, MetaValue)], + tensors: &[(&str, Vec, Vec)], +) -> WeightFile { + WeightFile::open(Box::new(Memory(bytes(metadata, tensors)))).expect("a test GGUF") +} + +/// The header of a GGUF with `metadata` and `tensors` (name, dims, ggml +/// type) laid end to end, up to where the tensor data starts, and the bytes +/// of that data. +pub(crate) fn header( + metadata: &[(&str, MetaValue)], + tensors: &[(&str, Vec, u32)], +) -> (Vec, u64) { + let mut out = b"GGUF".to_vec(); + out.extend(3u32.to_le_bytes()); + out.extend((tensors.len() as u64).to_le_bytes()); + out.extend((metadata.len() as u64).to_le_bytes()); + for (key, value) in metadata { + string(&mut out, key); + match value { + MetaValue::Int(v) => { + out.extend(10u32.to_le_bytes()); + out.extend(v.to_le_bytes()); + } + MetaValue::Float(v) => { + out.extend(12u32.to_le_bytes()); + out.extend(v.to_le_bytes()); + } + MetaValue::Str(v) => { + out.extend(8u32.to_le_bytes()); + string(&mut out, v); + } + MetaValue::Tokens(tokens) => { + out.extend(9u32.to_le_bytes()); + out.extend(5u32.to_le_bytes()); + out.extend((tokens.len() as u64).to_le_bytes()); + for token in tokens { + out.extend(token.to_le_bytes()); + } + } + } + } + let mut offset = 0u64; + for (name, dims, ggml_type) in tensors { + string(&mut out, name); + out.extend((dims.len() as u32).to_le_bytes()); + for d in dims { + out.extend(d.to_le_bytes()); + } + out.extend(ggml_type.to_le_bytes()); + out.extend(offset.to_le_bytes()); + let (block, bytes) = type_layout(*ggml_type).expect("a ggml type with a layout"); + let size = dims.iter().product::() / block * bytes; + offset += size.div_ceil(32) * 32; + } + out.resize(out.len().div_ceil(32) * 32, 0); + (out, offset) +} + +/// The bytes of a GGUF with `metadata` and f32 `tensors`. +pub(crate) fn bytes( + metadata: &[(&str, MetaValue)], + tensors: &[(&str, Vec, Vec)], +) -> Vec { + let listed: Vec<_> = tensors + .iter() + .map(|(name, dims, values)| { + assert_eq!( + dims.iter().product::(), + values.len() as u64, + "{name} has a value per element" + ); + (*name, dims.clone(), GGML_F32) + }) + .collect(); + let (mut out, _) = header(metadata, &listed); + for (_, _, values) in tensors { + for v in values { + out.extend(v.to_le_bytes()); + } + out.resize(out.len().div_ceil(32) * 32, 0); + } + out +} diff --git a/crates/skippy-receipts/src/weights/tests.rs b/crates/skippy-receipts/src/weights/tests.rs new file mode 100644 index 00000000..0eccf476 --- /dev/null +++ b/crates/skippy-receipts/src/weights/tests.rs @@ -0,0 +1,305 @@ +use super::limits::{AUDIT_FETCH_BUDGET, CannotAudit, MAX_HEADER_BYTES}; +use super::*; +use crate::ggml_types::{GGML_F32, GGML_Q4_K, GGML_Q8_0}; + +#[test] +fn rows_are_read_in_order_across_chunks() { + let weights = test_gguf::open( + &[], + &[("w", vec![2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])], + ); + let mut seen = Vec::new(); + weights + .each_row("w", 1..3, &mut |row, values| { + seen.push((row, values.to_vec())) + }) + .unwrap(); + assert_eq!(seen, vec![(1, vec![3.0, 4.0]), (2, vec![5.0, 6.0])]); + assert!(weights.each_row("w", 0..4, &mut |_, _| {}).is_err()); +} + +fn shard(no: u64, tensors: &[(&str, Vec, Vec)]) -> Box { + let mut metadata = vec![ + ("split.no", MetaValue::Int(no)), + ("split.count", MetaValue::Int(2)), + ]; + if no == 0 { + metadata.push(("general.architecture", MetaValue::Str("test".into()))); + metadata.push(("split.tensors.count", MetaValue::Int(2))); + } + Box::new(test_gguf::Memory(test_gguf::bytes(&metadata, tensors))) +} + +#[test] +fn a_split_gguf_reads_as_one_file() { + let weights = WeightFile::open_shards(vec![ + shard(0, &[("a", vec![2, 1], vec![1.0, 2.0])]), + shard(1, &[("b", vec![2, 2], vec![3.0, 4.0, 5.0, 6.0])]), + ]) + .unwrap(); + assert_eq!( + weights.metadata_str("general.architecture").unwrap(), + "test" + ); + assert_eq!(weights.row("a", 0).unwrap(), vec![1.0, 2.0]); + assert_eq!(weights.row("b", 1).unwrap(), vec![5.0, 6.0]); + let (offset, len) = weights.row_range("b", 1).unwrap(); + let bytes = weights.source.read_at(offset, len).unwrap(); + let expected: Vec = [5.0f32, 6.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + assert_eq!(bytes, expected); +} + +#[test] +fn shards_out_of_order_are_refused() { + let swapped = WeightFile::open_shards(vec![ + shard(1, &[("b", vec![2, 2], vec![3.0, 4.0, 5.0, 6.0])]), + shard(0, &[("a", vec![2, 1], vec![1.0, 2.0])]), + ]); + assert!(swapped.is_err()); +} + +fn refused(result: Result) -> String { + let error = result.err().expect("the file is refused"); + assert!(CannotAudit::caused(&error), "{error:#}"); + format!("{error:#}") +} + +#[test] +fn a_tensor_in_two_shards_is_refused() { + let twice = WeightFile::open_shards(vec![ + shard(0, &[("a", vec![2, 1], vec![1.0, 2.0])]), + shard(1, &[("a", vec![2, 1], vec![1.0, 2.0])]), + ]); + assert!(refused(twice).contains("in two of its shards")); +} + +#[test] +fn too_many_shards_are_refused_before_any_is_read() { + /// A shard that fails the test when it is read. + struct Unread; + impl ByteSource for Unread { + fn read_at(&self, _offset: u64, _len: u64) -> Result> { + panic!("a shard past the limit was read") + } + fn size(&self) -> u64 { + 1 << 20 + } + } + let shards = (0..=MAX_SHARDS) + .map(|_| Box::new(Unread) as Box) + .collect(); + assert!(refused(WeightFile::open_shards(shards)).contains("shards")); + assert!(refused(WeightFile::open_shards(Vec::new())).contains("shards")); +} + +/// A model with one matrix `w` of two rows, whose tensor a test then edits +/// to what a header must never give: the reads are errors, not panics. +fn edited(edit: impl FnOnce(&mut TensorInfo)) -> WeightFile { + let mut weights = test_gguf::open(&[], &[("w", vec![32, 2], vec![0.5; 64])]); + edit(weights.tensors.get_mut("w").unwrap()); + weights +} + +fn every_read_fails(weights: &WeightFile) { + assert!(weights.row("w", 0).is_err()); + assert!(weights.min_blocks("w", 0).is_err()); + assert!(weights.row_range("w", 0).is_err()); + assert!(weights.each_row("w", 0..1, &mut |_, _| {}).is_err()); + assert!(weights.stream_rows("w", 0..1, &mut |_, _| {}).is_err()); +} + +#[test] +fn a_row_shorter_than_a_block_is_an_error_not_a_panic() { + // 16 values of a type with blocks of 32, and of 256: no bytes per row + for (ggml_type, row_len) in [(GGML_Q8_0, 16), (GGML_Q4_K, 32), (GGML_Q4_K, 255)] { + let weights = edited(|t| { + t.ggml_type = ggml_type; + t.dims[0] = row_len; + }); + every_read_fails(&weights); + assert!(weights.tensor_range("w").is_err()); + assert!(weights.tensors["w"].row_bytes().is_err()); + assert!(weights.tensors["w"].total_bytes().is_err()); + } + let empty = edited(|t| t.dims[0] = 0); + every_read_fails(&empty); + assert!(empty.tensors["w"].total_bytes().is_err()); +} + +#[test] +fn sizes_that_wrap_are_errors() { + let huge_rows = edited(|t| t.dims[1] = u64::MAX); + assert!(huge_rows.tensors["w"].total_bytes().is_err()); + assert!(huge_rows.row_range("w", u64::MAX - 1).is_err()); + let wrapped = edited(|t| t.dims = vec![1 << 32, 1 << 32]); + assert!(wrapped.tensors["w"].row_count().is_ok()); + assert!(wrapped.tensors["w"].total_bytes().is_err()); + let long_row = edited(|t| t.dims[0] = u64::MAX - 31); + assert!(long_row.tensors["w"].row_bytes().is_err()); + every_read_fails(&long_row); + let far = edited(|t| t.offset = u64::MAX - 8); + assert!(far.row_range("w", 1).is_err()); + assert!(far.row("w", 1).is_err()); + // the layer's bytes saturate; they do not wrap + let names = ["blk.0.a.weight", "blk.0.b.weight"]; + let tensors: Vec<_> = names + .iter() + .map(|name| (*name, vec![32, 2], vec![0.5; 64])) + .collect(); + let mut layer = test_gguf::open(&[], &tensors); + for name in names { + // 2^63 bytes each + layer.tensors.get_mut(name).unwrap().dims[1] = 1 << 56; + } + assert_eq!(layer.layer_bytes()[&0], u64::MAX); +} + +#[test] +fn a_tensor_of_an_unknown_type_has_no_size() { + for ggml_type in [4, 5, 31, 36, 44, u32::MAX] { + let weights = edited(|t| t.ggml_type = ggml_type); + let error = weights.tensors["w"].total_bytes().unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(weights.tensor_range("w").is_err()); + every_read_fails(&weights); + } + // a type ggml has and the verifier does not decode still has a size + let sized = edited(|t| t.ggml_type = 19); + assert!( + sized.tensors["w"].total_bytes().is_err(), + "32 is not a block of 256" + ); + let sized = edited(|t| { + t.ggml_type = 19; + t.dims[0] = 256; + }); + assert_eq!(sized.tensors["w"].total_bytes().unwrap(), 100); +} + +#[test] +fn a_row_past_the_tensor_is_refused() { + let weights = test_gguf::open( + &[], + &[ + ("w", vec![2, 2], vec![1.0, 2.0, 3.0, 4.0]), + ("after", vec![2, 1], vec![9.0, 9.0]), + ], + ); + assert_eq!(weights.row("w", 1).unwrap(), vec![3.0, 4.0]); + assert!(weights.row("w", 2).is_err()); + assert!(weights.min_blocks("w", 2).is_err()); + assert!(weights.row_range("w", 2).is_err()); +} + +#[test] +fn a_row_of_too_many_values_is_refused() { + let weights = edited(|t| t.dims[0] = MAX_ROW_VALUES + 32); + let error = weights.row("w", 0).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + let error = weights.each_row("w", 0..1, &mut |_, _| {}).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); +} + +/// A remote model: its header is held, and every tensor byte is fetched. +/// `w` has 1024 rows of 32 values, 128 bytes each. +fn remote() -> WeightFile { + let (header, data) = test_gguf::header(&[], &[("w", vec![32, 1024], GGML_F32)]); + let size = header.len() as u64 + data; + WeightFile::open_with_budget( + Box::new(test_gguf::Remote::new(header, size)), + AUDIT_FETCH_BUDGET, + ) + .unwrap() +} + +#[test] +fn reads_of_a_remote_file_stop_at_the_budget() { + let weights = remote(); + // the first read of the header, which takes the whole small file, + // counts against the budget + assert_eq!(weights.fetched_bytes(), 1024 * 128); + weights.set_fetch_budget(300); + weights.row("w", 0).unwrap(); + weights + .prefetch(&[weights.row_range("w", 1).unwrap()]) + .unwrap(); + assert_eq!(weights.fetched_bytes(), 256); + let error = weights.row("w", 2).unwrap_err(); + assert!(CannotAudit::caused(&error), "{error:#}"); + assert!(error.to_string().contains("budget of 300 bytes"), "{error}"); + let range = weights.tensor_range("w").unwrap(); + assert!(weights.prefetch(&[range]).is_err()); + assert!(weights.min_blocks("w", 3).is_err()); + assert!(weights.each_row("w", 4..5, &mut |_, _| {}).is_err()); + assert!(weights.stream_rows("w", 4..5, &mut |_, _| {}).is_err()); + // what was refused was not spent + assert_eq!(weights.fetched_bytes(), 256); + // the next audit against the open file starts over + weights.reset_fetch_budget(); + weights.stream_rows("w", 4..6, &mut |_, _| {}).unwrap(); + assert_eq!(weights.fetched_bytes(), 256); + assert!(weights.row("w", 9).is_err()); +} + +#[test] +fn the_audit_budget_holds_a_whole_output_matrix() { + let weights = remote(); + weights.set_fetch_budget(AUDIT_FETCH_BUDGET); + weights.stream_rows("w", 0..1024, &mut |_, _| {}).unwrap(); + assert_eq!(weights.fetched_bytes(), 1024 * 128); + // Qwen3.5-397B-A17B: a 16-bit output matrix, a header at its limit, + // and four expert routers of 8 MiB + const NEEDED: u64 = 248_320 * 4_096 * 2 + MAX_HEADER_BYTES + 4 * (8 << 20); + const { assert!(AUDIT_FETCH_BUDGET >= NEEDED) }; + const { assert!(AUDIT_FETCH_BUDGET <= 2 * NEEDED) }; +} + +#[test] +fn a_local_file_spends_no_budget() { + let weights = test_gguf::open(&[], &[("w", vec![2, 2], vec![1.0, 2.0, 3.0, 4.0])]); + weights.set_fetch_budget(0); + assert_eq!(weights.row("w", 1).unwrap(), vec![3.0, 4.0]); + weights + .prefetch(&[weights.tensor_range("w").unwrap()]) + .unwrap(); + assert_eq!(weights.fetched_bytes(), 0); +} + +/// A remote file of which nothing is held: every byte read is fetched. +struct Unheld(Vec); + +impl ByteSource for Unheld { + fn read_at(&self, offset: u64, len: u64) -> Result> { + test_gguf::Memory(self.0.clone()).read_at(offset, len) + } + + fn size(&self) -> u64 { + self.0.len() as u64 + } + + fn missing_bytes(&self, ranges: &[(u64, u64)]) -> Result { + Ok(ranges.iter().map(|(_, len)| len).sum()) + } +} + +#[test] +fn the_header_counts_against_the_budget() { + let bytes = test_gguf::bytes(&[], &[("w", vec![2, 2], vec![1.0, 2.0, 3.0, 4.0])]); + let size = bytes.len() as u64; + let opened = WeightFile::open_with_budget(Box::new(Unheld(bytes.clone())), size).unwrap(); + let header = opened.fetched_bytes(); + assert!(header > 0 && header <= size, "{header}"); + // the first audit counts the header; the next starts over + opened.reset_fetch_budget(); + assert_eq!(opened.fetched_bytes(), header); + opened.reset_fetch_budget(); + assert_eq!(opened.fetched_bytes(), 0); + // a budget that does not hold the header opens nothing + let refused = WeightFile::open_with_budget(Box::new(Unheld(bytes.clone())), 8) + .err() + .unwrap(); + assert!(CannotAudit::caused(&refused), "{refused:#}"); + // nor does a remote file opened as one held whole + let refused = WeightFile::open(Box::new(Unheld(bytes))).err().unwrap(); + assert!(CannotAudit::caused(&refused), "{refused:#}"); +} diff --git a/crates/skippy-receipts/src/wire.rs b/crates/skippy-receipts/src/wire.rs new file mode 100644 index 00000000..ea48c08d --- /dev/null +++ b/crates/skippy-receipts/src/wire.rs @@ -0,0 +1,780 @@ +//! JSON shapes exchanged between the serving node and the auditing client. + +use anyhow::{Context, Result, bail}; +use base64::Engine; +use serde::{Deserialize, Serialize}; + +use crate::attention::opening::{AttentionPartials, AttentionPick}; +use crate::commitment::MixingValue; +use crate::layer_tensors::TensorKind; + +/// The receipt format. A receipt carries the signed [`crate::turn::TurnBinding`] +/// and binds each committed value by its BLAKE3 digest +/// ([`crate::commitment::ValueDigest`]). A mixing leaf hashes its stored rows +/// apart from its other values, and a cell's digest covers its stored rows +/// alone, so an attention check can open the rows a turn attended to. On a +/// hybrid model the receipt binds the recurrent state the turn started from, +/// and the mixing leaf of each ubatch's first position commits the state the +/// ubatch read, so a client can recompute the ubatch. The node's signature +/// of an opening covers the challenge it answers, and its signature of +/// attention rows covers the blocks they answer. A stage binds, for every +/// position of a cached prefix, the leaves it committed when it computed +/// the position, and the stage that holds layer 0 binds the prefix's +/// tokens, so a client can challenge a position the turn read from cache. +pub const RECEIPT_VERSION: u32 = 7; + +/// What the node claims it ran, attached to a response. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Receipt { + pub version: u32, + /// Response id; the key for challenges. + pub receipt_id: String, + /// The GGUF the node claims, as configured by the operator. + pub model: String, + /// First and one-past-last sequence position the turn computed. + pub position_start: u32, + pub position_end: u32, + /// The token at every position of the turn, from `position_start`. The + /// stage holding layer 0 binds each one into the residual leaf of layer 0. + pub tokens: Vec, + /// The first position whose token this turn sampled. Earlier positions + /// hold the prompt. + pub generation_start: u32, + /// The last token the turn sampled, which no position holds. + pub final_token: Option, + pub stages: Vec, + /// The client key, parent turn and runtime, and the node's signature + /// of the turn root. Absent when the request named no client key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub binding: Option, +} + +/// One stage's commitment to the turn: a Merkle root over its leaves. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct StageCommitment { + pub stage_index: u32, + pub layer_start: u32, + pub layer_end: u32, + /// Hex BLAKE3 Merkle root over leaves ordered by position, then slot + /// (see `commitment`). + pub root: String, + pub leaf_count: u64, + /// Backend facts the verifier needs to pick rounding profiles. + pub backend: String, + /// ggml type names of the KV cache and state rows the stage stored, + /// for example `f16` or `q8_0`. A client decides which it accepts. + #[serde(default)] + pub cache_types: Vec, + /// The KV cells the turn attended to below its first replayed position, + /// computed before the turn. `None` when the turn starts at position 0. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prefix: Option, + /// The first position of every ubatch that computed positions of the + /// turn, in order: the batch geometry a verifier's rounding depends on. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub ubatches: Vec, + /// On a stage with hybrid memory, the hex digest of the recurrent state + /// the turn started from ([`crate::commitment::recurrent_state_digest`]). + /// A replay of the turn starts from that state. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recurrent_state: Option, +} + +/// A stage's commitment to the cached prefix a turn started from. +/// +/// One leaf per position `0..positions`, in order: the position, the KV +/// cell that held it, the digest of the rows the cell stores, and the +/// digest of the leaves the stage committed when it computed that position +/// ([`crate::commitment::prefix_leaf`]). A replay of the turn starts from +/// those cells instead of recomputing the prefix. A client that challenges +/// a position of the prefix gets its leaves ([`PrefixOpening`]) and checks +/// them as it checks a position the turn computed. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct PrefixCommitment { + /// Hex BLAKE3 Merkle root over the prefix leaves. + pub root: String, + pub positions: u32, + /// Hex digest of the prefix's tokens, from position 0 + /// ([`crate::commitment::prefix_tokens_digest`]). The stage that holds + /// layer 0 commits it, and no other stage does. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +impl Receipt { + pub fn stage_for_layer(&self, layer: u32) -> Option<&StageCommitment> { + self.stages + .iter() + .find(|stage| (stage.layer_start..stage.layer_end).contains(&layer)) + } + + pub fn layer_count(&self) -> u32 { + self.stages.iter().map(|s| s.layer_end).max().unwrap_or(0) + } + + /// The token at `position`, if the turn computed it. + pub fn token_at(&self, position: u32) -> Option { + let offset = position.checked_sub(self.position_start)?; + self.tokens.get(usize::try_from(offset).ok()?).copied() + } + + /// Positions whose output the turn sampled a token from, in order: the + /// last prompt position, when the turn computed it, and every position + /// after it. + pub(crate) fn output_positions(&self) -> std::ops::Range { + let first = self + .generation_start + .saturating_sub(1) + .max(self.position_start); + let end = if self.final_token.is_some() { + self.position_end + } else { + self.position_end.saturating_sub(1) + }; + first..end.max(first) + } + + /// The token the turn sampled from the output at `position`. + pub(crate) fn sampled_after(&self, position: u32) -> Option { + if !self.output_positions().contains(&position) { + return None; + } + if position + 1 == self.position_end { + self.final_token + } else { + self.token_at(position + 1) + } + } + + /// The tokens the turn sampled, in order. + pub fn sampled_tokens(&self) -> Vec { + let start = self.generation_start.saturating_sub(self.position_start) as usize; + let mut sampled = self.tokens.get(start..).unwrap_or_default().to_vec(); + sampled.extend(self.final_token); + sampled + } +} + +/// One challenged layer and the positions opened in it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct Pick { + pub layer: u32, + /// Absolute sequence positions, increasing: first the positions of the + /// turn's cached prefix that the challenge picks, the same in every + /// pick, then positions inside the receipt's range. + pub positions: Vec, +} + +/// The client's challenge, sent after the receipt arrives. Besides the +/// picked layers, every challenge opens the layer-0 input and the stage +/// boundaries at every picked position. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct Challenge { + pub receipt_id: String, + pub picks: Vec, + /// Hex VRF proof of the turn root under the receipt's client key, from + /// which the picks are drawn. Required when the receipt names a key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proof: Option, + /// Positions whose sampled token the client checks against the output + /// head, sorted. The final stage opens its output residual at each. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub head: Vec, + /// Positions of picked layers whose attention the client checks, with + /// a head each. A stage opens the head's partials at each one in a + /// layer with attention. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub attention: Vec, +} + +impl Challenge { + /// A digest of every field, which the node signs with its opening + /// ([`crate::turn::sign_opening`]): an opening is evidence only of the + /// challenge the node answered. + pub fn digest(&self) -> crate::commitment::Hash { + let mut h = blake3::Hasher::new_derive_key("mesh-llm receipts challenge v1"); + let text = |h: &mut blake3::Hasher, s: &str| { + h.update(&(s.len() as u64).to_le_bytes()); + h.update(s.as_bytes()); + }; + let count = |h: &mut blake3::Hasher, n: usize| { + h.update(&(n as u64).to_le_bytes()); + }; + text(&mut h, &self.receipt_id); + count(&mut h, self.picks.len()); + for pick in &self.picks { + h.update(&pick.layer.to_le_bytes()); + count(&mut h, pick.positions.len()); + for position in &pick.positions { + h.update(&position.to_le_bytes()); + } + } + match &self.proof { + Some(proof) => { + h.update(&[1]); + text(&mut h, proof); + } + None => { + h.update(&[0]); + } + } + count(&mut h, self.head.len()); + for position in &self.head { + h.update(&position.to_le_bytes()); + } + count(&mut h, self.attention.len()); + for pick in &self.attention { + h.update(&pick.position.to_le_bytes()); + h.update(&pick.layer.to_le_bytes()); + h.update(&pick.head_draw.to_le_bytes()); + } + *h.finalize().as_bytes() + } + + /// The picked positions below `turn_start`, the first position of the + /// turn: positions of its cached prefix, sorted and distinct. + pub fn prefix_positions(&self, turn_start: u32) -> Vec { + let mut positions = self.positions(); + positions.retain(|position| *position < turn_start); + positions + } + + /// Every picked position, sorted and distinct. + pub fn positions(&self) -> Vec { + let set: std::collections::BTreeSet = self + .picks + .iter() + .flat_map(|p| p.positions.iter().copied()) + .collect(); + set.into_iter().collect() + } +} + +/// The node's answer: one part per stage. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Opening { + pub receipt_id: String, + pub stages: Vec, +} + +impl Opening { + pub fn stage(&self, index: u32) -> Option<&StageOpening> { + self.stages.iter().find(|s| s.stage_index == index) + } +} + +/// What one stage opened: its picked layers, the layer-0 input if it holds +/// layer 0, and the leaves at its boundaries. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct StageOpening { + pub stage_index: u32, + pub layers: Vec, + /// The residual entering layer 0 with its token, at every picked + /// position. Only the stage holding layer 0 opens these. + #[serde(default)] + pub anchors: Vec, + /// The leaf of the residual entering the stage, at every picked + /// position. Empty for the stage holding layer 0. + #[serde(default)] + pub entry: Vec, + /// The leaf of the residual leaving the stage, at every picked position. + #[serde(default)] + pub exit: Vec, + /// The residual the output head reads, at every head position of the + /// challenge. Only the final stage opens these. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub head: Vec, + /// The partials of every attention pick of the challenge in a layer of + /// the stage that has attention. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub attention: Vec, + /// The recurrent token mixing of the first attention pick in a layer of + /// the stage that keeps a recurrent state. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub recurrent: Vec, + /// What the stage committed at every picked position of the turn's + /// cached prefix, in position order. The leaves of such a position are + /// opened without a path: they are checked against these. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub prefix: Vec, + /// The tokens of the turn's cached prefix, from position 0. Only the + /// stage holding layer 0 opens them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub prefix_tokens: Vec, +} + +/// One picked position of a turn's cached prefix: the leaves the stage +/// committed when it computed the position, and their place in the prefix +/// tree the receipt commits ([`PrefixCommitment`]). +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct PrefixOpening { + pub position: u32, + /// The index of the KV cell that held the position. + pub cell: u32, + /// Hex leaf hashes of the position, in slot order: what a stage commits + /// per position of a turn. + pub leaves: Vec, + /// Hex leaves of the rows each layer of the stage stored in the cell + /// ([`crate::commitment::stored_leaf`]), in layer order. Their Merkle + /// root is the cell's digest, which binds the rows an attention check + /// reads to the mixing leaves opened here. + pub stored: Vec, + /// Hex sibling hashes of the position's leaf in the prefix tree. + pub path: Vec, +} + +/// The ubatch that computed an attention pick in a layer that keeps a +/// recurrent state: the mixing values of each of its positions, and of the +/// position after it, whose leaf holds the state the ubatch left. A client +/// recomputes the token mixing from the inputs and the state the ubatch +/// read, and compares the outputs and the state it leaves. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct RecurrentOpening { + /// The attention pick. + pub position: u32, + pub layer: u32, + /// The ubatch's positions of the turn's sequence: `start..end`. + pub start: u32, + pub end: u32, + /// From `start` to `end`, or to `end - 1` when the turn ends there. + pub leaves: Vec, +} + +/// One position's mixing leaf: its values and Merkle path. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct MixingLeafOpening { + pub position: u32, + pub mixing: Vec, + pub path: Vec, +} + +/// The residual leaving the model's final layer at one position, which the +/// output head turns into the logits the token was sampled from. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct HeadOpening { + pub position: u32, + /// Base64 little-endian f32. + pub residual: String, + pub path: Vec, + /// The logits the node computed from the residual, base64 little-endian + /// f32, one per vocabulary token. A client with a head key checks them + /// instead of computing the whole output matrix. Absent from nodes that + /// predate them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub logits: Option, +} + +impl HeadOpening { + pub(crate) fn residual_values(&self) -> Result> { + decode_f32(&self.residual).context("decode an output residual") + } + + pub fn logit_values(&self) -> Result>> { + self.logits + .as_deref() + .map(|text| decode_f32(text).context("decode opened logits")) + .transpose() + } +} + +/// The challenged leaves of one layer, and its weight matmuls and +/// selections recomputed by replay. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct LayerOpening { + pub layer: u32, + pub leaves: Vec, +} + +/// The residual entering layer 0 at one position, which the auditor +/// recomputes from the token. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct AnchorOpening { + pub position: u32, + pub token: i32, + /// Base64 little-endian f32. + pub residual: String, + pub path: Vec, +} + +impl AnchorOpening { + pub(crate) fn residual_values(&self) -> Result> { + decode_f32(&self.residual).context("decode an anchor residual") + } +} + +/// A residual leaf at a stage boundary, by hash: two stages commit the same +/// row, so the leaf must be the same in both trees. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct BoundaryLeaf { + pub position: u32, + /// Hex leaf hash. + pub leaf: String, + pub path: Vec, +} + +/// One challenged position: the layer's committed leaves with their Merkle +/// paths, and the layer's weight matmuls and selections recomputed by replay. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct LeafOpening { + pub position: u32, + /// Residual stream entering the layer, base64 little-endian f32. + pub residual_in: String, + /// Residual stream leaving the layer. Absent where the layer kept no row + /// for this position (the final layer of a final stage, non-output rows). + pub residual_out: Option, + /// Hex sibling hashes, leaf to root, of the residual-in, mixing and + /// residual-out leaves. + pub residual_in_path: Vec, + pub mixing_path: Vec, + pub residual_out_path: Vec, + /// The mixing leaf's values, in leaf order. + pub mixing: Vec, + /// The layer's weight matmuls at this position, by index. Matmuls after + /// the layer dropped this position's row are absent. + pub matrices: Vec, + pub selections: Vec, +} + +impl LeafOpening { + pub fn residual_in_values(&self) -> Result> { + decode_f32(&self.residual_in).context("decode residual_in") + } + + pub(crate) fn residual_out_values(&self) -> Result>> { + self.residual_out + .as_deref() + .map(|text| decode_f32(text).context("decode residual_out")) + .transpose() + } + + pub fn matrix(&self, index: u32) -> Option<&MatrixOpening> { + self.matrices.iter().find(|m| m.index == index) + } + + pub fn mixing_value(&self, kind: MixingKind, index: u32) -> Option<&TensorOpening> { + self.mixing + .iter() + .find(|t| t.kind == kind && t.index == index) + } + + pub fn selection(&self, index: u32) -> Option<&SelectionOpening> { + self.selections.iter().find(|s| s.index == index) + } +} + +/// Which part of a token-mixing op a value is. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(rename_all = "snake_case")] +pub enum MixingKind { + Input, + /// A KV cache row as stored, in the cache's type. + Stored, + Output, + /// The recurrent state a sequence starts the ubatch from, in the leaf of + /// its first position. + State, +} + +impl MixingKind { + pub(crate) fn tensor_kind(self) -> TensorKind { + match self { + Self::Input => TensorKind::MixingInput, + Self::Stored => TensorKind::MixingStored, + Self::Output => TensorKind::MixingOutput, + Self::State => TensorKind::MixingState, + } + } + + pub(crate) fn from_tensor_kind(kind: TensorKind) -> Option { + match kind { + TensorKind::MixingInput => Some(Self::Input), + TensorKind::MixingStored => Some(Self::Stored), + TensorKind::MixingOutput => Some(Self::Output), + TensorKind::MixingState => Some(Self::State), + _ => None, + } + } +} + +/// One committed token-mixing value. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TensorOpening { + pub kind: MixingKind, + pub index: u32, + /// ggml type of the values. + pub ggml_type: i32, + /// Base64 little-endian values; absent where the layer kept no row. + pub values: Option, +} + +impl TensorOpening { + pub fn new(kind: MixingKind, index: u32, value: Option<(i32, &[u8])>) -> Self { + Self { + kind, + index, + ggml_type: value.map_or(crate::layer_tensors::GGML_F32, |(t, _)| t), + values: value.map(|(_, bytes)| encode_bytes(bytes)), + } + } + + pub fn bytes(&self) -> Result>> { + self.values + .as_deref() + .map(|text| decode_bytes(text).context("decode a mixing value")) + .transpose() + } + + /// The f32 values; an error for another type. + pub(crate) fn f32_values(&self) -> Result>> { + if self.ggml_type != crate::layer_tensors::GGML_F32 { + bail!("mixing value {:?} {} is not f32", self.kind, self.index); + } + Ok(self + .bytes()? + .map(|bytes| crate::layer_tensors::decode_f32_bytes(&bytes))) + } +} + +/// A mixing value decoded for hashing: kind, index, ggml type and bytes. +pub(crate) type DecodedMixing = (MixingKind, u32, i32, Option>); + +/// Decodes the mixing values of a leaf for hashing. +pub(crate) fn mixing_bytes(values: &[TensorOpening]) -> Result> { + values + .iter() + .map(|t| Ok((t.kind, t.index, t.ggml_type, t.bytes()?))) + .collect() +} + +/// Borrows decoded mixing values as leaf inputs. +pub(crate) fn mixing_values(decoded: &[DecodedMixing]) -> Vec> { + decoded + .iter() + .map(|(kind, index, ggml_type, bytes)| MixingValue { + kind: kind.tensor_kind(), + index: *index, + value: bytes.as_deref().map(|b| (*ggml_type, b)), + }) + .collect() +} + +/// One weight matmul for one token: `output = weight · input`. For a +/// `mul_mat_id`, one slice of input and output per expert used. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct MatrixOpening { + /// Ordinal among the layer's weight matmuls. + pub index: u32, + /// GGUF tensor name, e.g. `blk.12.attn_q.weight`. + pub weight: String, + /// The output feeds a selection (MoE routing); every row is checked. + #[serde(default)] + pub router: bool, + /// The experts a `mul_mat_id` used, one per output slice. + #[serde(default)] + pub experts: Option>, + /// Base64 little-endian f32. + pub input: String, + pub output: String, +} + +impl MatrixOpening { + pub(crate) fn input_values(&self) -> Result> { + decode_f32(&self.input).with_context(|| format!("decode input of {}", self.weight)) + } + + pub(crate) fn output_values(&self) -> Result> { + decode_f32(&self.output).with_context(|| format!("decode output of {}", self.weight)) + } + + /// How many values the input and output hold, without decoding them. + /// Fails where [`Self::input_values`] or [`Self::output_values`] would. + pub(crate) fn value_counts(&self) -> Result<(usize, usize)> { + let input = + f32_count(&self.input).with_context(|| format!("decode input of {}", self.weight))?; + let output = + f32_count(&self.output).with_context(|| format!("decode output of {}", self.weight))?; + Ok((input, output)) + } +} + +/// The ids a selection (`argsort` or top-k) picked for one token. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SelectionOpening { + pub index: u32, + pub ids: Vec, +} + +/// Why a stage can no longer open a turn it committed. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CannotOpenReason { + /// The turn left the stage's opening window: it was committed too long + /// ago, or the window was full. + Expired, + /// A later request wrote a KV cell the opening reads: the cache was + /// full, or the turn was no longer pinned. + CellsOverwritten, + /// The stage no longer knows what a KV cell the opening reads holds: a + /// ubatch it could not record, a state load, a compaction or a clear + /// changed its cache since. + CellsUnknown, + /// The stage dropped the recurrent state the turn started from. + StateDropped, +} + +/// A stage's answer to a well-formed challenge it can no longer open, +/// because state of its own is gone. A client tells it from a refused or +/// malformed request by its HTTP status (410 for [`CannotOpenReason::Expired`], +/// else 409) and its `cannot_open` body, and for a bound receipt by the +/// node's signature of it ([`crate::turn::sign_cannot_open`]). +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct CannotOpen { + pub receipt_id: String, + /// The stage that cannot open. + pub stage_index: u32, + pub reason: CannotOpenReason, + /// What the stage found, for a reader. + pub detail: String, +} + +impl std::fmt::Display for CannotOpen { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "stage {} can no longer open receipt {}: {}", + self.stage_index, self.receipt_id, self.detail + ) + } +} + +impl std::error::Error for CannotOpen {} + +pub fn encode_f32(values: &[f32]) -> String { + encode_bytes(&crate::layer_tensors::f32_bytes(values)) +} + +pub(crate) fn encode_bytes(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +pub(crate) fn decode_bytes(text: &str) -> Result> { + Ok(base64::engine::general_purpose::STANDARD.decode(text)?) +} + +/// How many values [`decode_f32`] decodes from `text`, without decoding it. +/// Fails on text it would refuse: not padded base64, or not whole f32s. +fn f32_count(text: &str) -> Result { + let bytes = text.as_bytes(); + let padding = bytes.iter().rev().take_while(|&&b| b == b'=').count(); + let digits = &bytes[..bytes.len() - padding]; + let digit = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/'; + if !bytes.len().is_multiple_of(4) || padding > 2 || !digits.iter().all(digit) { + bail!("not base64: {} characters", bytes.len()); + } + let len = bytes.len() / 4 * 3 - padding; + if !len.is_multiple_of(4) { + bail!("f32 payload of {len} bytes"); + } + Ok(len / 4) +} + +pub(crate) fn decode_f32(text: &str) -> Result> { + let bytes = decode_bytes(text)?; + if bytes.len() % 4 != 0 { + bail!("f32 payload of {} bytes", bytes.len()); + } + Ok(crate::layer_tensors::decode_f32_bytes(&bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn f32_round_trip_is_bit_exact() { + let values = [0.0f32, -1.5, f32::MIN_POSITIVE, 3.25e-7, f32::MAX]; + assert_eq!(decode_f32(&encode_f32(&values)).unwrap(), values); + } + + #[test] + fn f32_count_matches_the_decoded_values() { + for n in 0..9 { + let values = vec![1.0f32; n]; + assert_eq!(f32_count(&encode_f32(&values)).unwrap(), n); + } + for bad in ["AAA", "AA@A", "AAAAAA=", "A===", "AAAA"] { + assert!(decode_f32(bad).is_err(), "{bad}"); + assert!(f32_count(bad).is_err(), "{bad}"); + } + } + + #[test] + fn stage_lookup_uses_half_open_ranges() { + let stage = |index, start, end| StageCommitment { + stage_index: index, + layer_start: start, + layer_end: end, + root: String::new(), + leaf_count: 0, + backend: String::new(), + cache_types: Vec::new(), + prefix: None, + ubatches: Vec::new(), + recurrent_state: None, + }; + let receipt = Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: 0, + position_end: 1, + tokens: vec![5], + generation_start: 1, + final_token: Some(6), + stages: vec![stage(0, 0, 18), stage(1, 18, 36)], + binding: None, + }; + assert_eq!(receipt.stage_for_layer(17).unwrap().stage_index, 0); + assert_eq!(receipt.stage_for_layer(18).unwrap().stage_index, 1); + assert!(receipt.stage_for_layer(36).is_none()); + assert_eq!(receipt.layer_count(), 36); + assert_eq!(receipt.token_at(0), Some(5)); + assert_eq!(receipt.token_at(1), None); + assert_eq!(receipt.sampled_tokens(), vec![6]); + assert_eq!(receipt.output_positions(), 0..1); + assert_eq!(receipt.sampled_after(0), Some(6)); + } + + #[test] + fn output_positions_are_the_ones_tokens_were_sampled_from() { + let receipt = |start, generation, end, final_token| Receipt { + version: RECEIPT_VERSION, + receipt_id: "r".into(), + model: "m".into(), + position_start: start, + position_end: end, + tokens: (start as i32..end as i32).collect(), + generation_start: generation, + final_token, + stages: Vec::new(), + binding: None, + }; + // prompt 0..4, sampled tokens at 4..6 and a final one + let r = receipt(0, 4, 6, Some(9)); + assert_eq!(r.output_positions(), 3..6); + assert_eq!(r.sampled_after(3), Some(4)); + assert_eq!(r.sampled_after(5), Some(9)); + assert_eq!(r.sampled_after(2), None); + // the turn continues a cached prefix it did not compute + let r = receipt(10, 10, 12, Some(9)); + assert_eq!(r.output_positions(), 10..12); + assert_eq!(r.sampled_after(10), Some(11)); + // no sampled token at all + let r = receipt(0, 4, 4, None); + assert!(r.output_positions().is_empty()); + // a turn that stopped without a final token + let r = receipt(0, 2, 4, None); + assert_eq!(r.output_positions(), 1..3); + assert_eq!(r.sampled_after(2), Some(3)); + } +} diff --git a/crates/skippy-receipts/tests/fixtures/metal/legacy.f32le b/crates/skippy-receipts/tests/fixtures/metal/legacy.f32le new file mode 100644 index 00000000..23b7c73d Binary files /dev/null and b/crates/skippy-receipts/tests/fixtures/metal/legacy.f32le differ diff --git a/crates/skippy-receipts/tests/fixtures/metal/tensor.f32le b/crates/skippy-receipts/tests/fixtures/metal/tensor.f32le new file mode 100644 index 00000000..27db4c46 Binary files /dev/null and b/crates/skippy-receipts/tests/fixtures/metal/tensor.f32le differ diff --git a/crates/skippy-receipts/tests/layers.rs b/crates/skippy-receipts/tests/layers.rs new file mode 100644 index 00000000..369d4cf2 --- /dev/null +++ b/crates/skippy-receipts/tests/layers.rs @@ -0,0 +1,635 @@ +//! The layers of `skippy-receipts`, checked against the source. +//! +//! `src/lib.rs` puts every top-level module under a `// Layer:` comment: +//! shared, node, client or test support. This test reads those comments +//! and every file under `src/`, and fails when a module names, through a +//! `crate::` path, a module of a layer that it may not use: +//! +//! - a shared module uses shared modules only; +//! - a node module uses shared and node modules; +//! - a client module uses shared and client modules; +//! - test support and test code use every layer. +//! +//! Test code is a module declared under a `cfg` that names `test` (a +//! `tests.rs` file, an inline `mod tests`, the `test-support` feature), and +//! everything inside it. Comments are not code, so a doc comment may point +//! at any module. +//! +//! The check reads `crate::` paths. A `super::` path that leaves its +//! top-level module would get around it, so that fails too. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Layer { + Shared, + Node, + Client, + TestSupport, +} + +impl Layer { + /// The layer a `// Layer:` comment of `src/lib.rs` names. + fn named(name: &str) -> Option { + Some(match name { + "shared" => Self::Shared, + "node" => Self::Node, + "client" => Self::Client, + "test support" => Self::TestSupport, + _ => return None, + }) + } + + fn name(self) -> &'static str { + match self { + Self::Shared => "shared", + Self::Node => "node", + Self::Client => "client", + Self::TestSupport => "test support", + } + } + + /// Whether a module of this layer may name a module of `other`. + fn may_use(self, other: Self) -> bool { + match self { + Self::Shared => other == Self::Shared, + Self::Node => matches!(other, Self::Shared | Self::Node), + Self::Client => matches!(other, Self::Shared | Self::Client), + Self::TestSupport => true, + } + } + + fn rule(self) -> &'static str { + match self { + Self::Shared => "A shared module may use shared modules only.", + Self::Node => "A node module may use shared and node modules.", + Self::Client => "A client module may use shared and client modules.", + Self::TestSupport => "Test support may use every layer.", + } + } +} + +/// The layer of each top-level module, from the `// Layer:` comments of +/// `src/lib.rs`. +fn layers_of(lib: &str) -> Result, String> { + let mut layers = BTreeMap::new(); + let mut current = None; + for line in lib.lines() { + if let Some(name) = line.trim().strip_prefix("// Layer:") { + let name = name.trim(); + let layer = Layer::named(name) + .ok_or_else(|| format!("src/lib.rs: `// Layer: {name}` names no layer"))?; + current = Some(layer); + } else if let Some((module, _)) = mod_declaration(line) { + let layer = current.ok_or_else(|| { + format!("src/lib.rs: `mod {module}` is above the first `// Layer:` comment") + })?; + layers.insert(module.to_owned(), layer); + } + } + Ok(layers) +} + +/// The name of the module a line declares, and whether its body follows +/// inline. +fn mod_declaration(line: &str) -> Option<(&str, bool)> { + let line = line.trim(); + let line = match line.strip_prefix("pub") { + Some(rest) if rest.starts_with('(') => rest.split_once(')')?.1.trim_start(), + Some(rest) if rest.starts_with(' ') => rest.trim_start(), + _ => line, + }; + let rest = line.strip_prefix("mod ")?; + let end = rest + .find(|c: char| !(c.is_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + let (name, tail) = rest.split_at(end); + match tail.trim() { + ";" => Some((name, false)), + tail if tail.starts_with('{') && !name.is_empty() => Some((name, true)), + _ => None, + } +} + +/// A `mod name;` line of a file. +#[derive(Debug, PartialEq, Eq)] +struct ChildModule { + name: String, + /// The file a `#[path]` attribute gives it. + path: Option, + /// Declared under a `cfg` that names `test`, or inside a test module. + test: bool, +} + +/// What the check reads of one source file. +#[derive(Debug, PartialEq, Eq)] +struct Source { + /// The file up to its inline test module, without comments. + code: String, + children: Vec, +} + +fn read_source(text: &str) -> Source { + let mut code = String::new(); + let mut children = Vec::new(); + let mut in_tests = false; + let (mut cfg_test, mut path) = (false, None); + for line in text.lines() { + let line = without_comment(line); + let trimmed = line.trim(); + if trimmed.starts_with("#[") { + cfg_test |= trimmed.starts_with("#[cfg(") && trimmed.contains("test"); + if let Some(file) = trimmed.strip_prefix("#[path = \"") { + path = file.split('"').next().map(str::to_owned); + } + } else if !trimmed.is_empty() { + match mod_declaration(trimmed) { + Some((name, false)) => children.push(ChildModule { + name: name.to_owned(), + path: path.take(), + test: in_tests || cfg_test, + }), + Some((_, true)) => in_tests |= cfg_test, + None => {} + } + (cfg_test, path) = (false, None); + } + // every line is kept, so that a position in `code` is a line of the file + if !in_tests { + code.push_str(line); + } + code.push('\n'); + } + Source { code, children } +} + +/// The line up to its `//` comment. A `//` inside a string literal is kept. +fn without_comment(line: &str) -> &str { + let mut in_string = false; + let mut previous = '\0'; + for (at, c) in line.char_indices() { + match c { + '"' if previous != '\\' => in_string = !in_string, + '/' if previous == '/' && !in_string => return &line[..at - 1], + _ => {} + } + previous = c; + } + line +} + +/// A path that leaves its module. +#[derive(Debug, PartialEq, Eq)] +enum Reference { + /// `crate::`. + Crate(String), + /// A `super::` chain of this length. + Super(usize), +} + +/// Every `crate::` path and `super::` chain of `code`, with its line. +fn references(code: &str) -> Vec<(usize, Reference)> { + let line_of = |at: usize| code[..at].matches('\n').count() + 1; + let starts_a_path = |at: usize| !code[..at].ends_with(is_name_char); + let mut found = Vec::new(); + for (at, keyword) in code.match_indices("crate::") { + if starts_a_path(at) { + let path = at + keyword.len(); + for (offset, name) in first_segments(&code[path..]) { + found.push((line_of(path + offset), Reference::Crate(name))); + } + } + } + for (at, keyword) in code.match_indices("super::") { + if starts_a_path(at) && !code[..at].ends_with(keyword) { + let chain = code[at..] + .split(keyword) + .take_while(|s| s.is_empty()) + .count(); + found.push((line_of(at), Reference::Super(chain))); + } + } + found.sort_by_key(|(line, _)| *line); + found +} + +fn is_name_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +/// The first segment of each path that `path` starts, with where it is in +/// `path`: one for `a::b`, one per branch for a group `{a::b, c}`. +fn first_segments(path: &str) -> Vec<(usize, String)> { + let Some(group) = path.strip_prefix('{') else { + return vec![(0, first_name(path))]; + }; + let mut segments = Vec::new(); + let (mut depth, mut start) = (0usize, 0); + let mut branch = |from: usize, to: usize| { + let text = &group[from..to]; + let skipped = text.len() - text.trim_start().len(); + if !text.trim().is_empty() { + segments.push((1 + from + skipped, first_name(text.trim_start()))); + } + }; + for (at, c) in group.char_indices() { + match c { + '{' => depth += 1, + '}' if depth == 0 => { + branch(start, at); + return segments; + } + '}' => depth -= 1, + ',' if depth == 0 => { + branch(start, at); + start = at + 1; + } + _ => {} + } + } + branch(start, group.len()); + segments +} + +fn first_name(path: &str) -> String { + path.chars().take_while(|c| is_name_char(*c)).collect() +} + +/// One module file as the check walks it. +struct Module<'a> { + /// Its file, relative to `src/`. + file: &'a Path, + /// Its top-level module, and that module's layer. + top: &'a str, + layer: Layer, + /// How many modules deep it is: 1 for a top-level module. + depth: usize, +} + +/// The paths of `code` that the layer of `module` may not hold. +fn violations(module: &Module<'_>, code: &str, layers: &BTreeMap) -> Vec { + let Module { + file, + top, + layer, + depth, + } = module; + let mut found = Vec::new(); + for (line, reference) in references(code) { + let at = format!("src/{}:{line}", file.display()); + match reference { + Reference::Crate(name) => match layers.get(&name) { + Some(other) if layer.may_use(*other) => {} + Some(other) => found.push(format!( + "{at}: `crate::{name}`. `{top}` is in the {} layer and `{name}` is in the {} \ + layer. {}", + layer.name(), + other.name(), + layer.rule() + )), + None => found.push(format!( + "{at}: `crate::{name}` is not a module that src/lib.rs puts in a layer. Name \ + the module that owns the item." + )), + }, + Reference::Super(chain) if chain >= *depth => found.push(format!( + "{at}: a `super::` path leaves `{top}`. Write it from `crate::`, so that this \ + check can read it." + )), + Reference::Super(_) => {} + } + } + found +} + +/// The file of a child module of `parent`. +fn child_file(src: &Path, parent: &Path, own_dir: bool, child: &ChildModule) -> Option { + let parent_dir = parent.parent().unwrap_or(Path::new("")); + if let Some(path) = &child.path { + return Some(parent_dir.join(path)); + } + let dir = if own_dir { + parent_dir.to_path_buf() + } else { + parent_dir.join(parent.file_stem()?) + }; + [ + dir.join(format!("{}.rs", child.name)), + dir.join(&child.name).join("mod.rs"), + ] + .into_iter() + .find(|file| src.join(file).is_file()) +} + +/// Walks the module tree of the crate at `src` and collects what breaks +/// the layering. +struct Walk<'a> { + src: &'a Path, + layers: &'a BTreeMap, + visited: BTreeSet, + problems: Vec, +} + +impl Walk<'_> { + /// Reads `module` and the modules it declares. `own_dir` says that its + /// children are in its own directory, as for `lib.rs` and a file that a + /// `#[path]` names. `test` says that it is test code. + fn module(&mut self, module: &Module<'_>, own_dir: bool, test: bool) { + let Ok(text) = fs::read_to_string(self.src.join(module.file)) else { + self.problems + .push(format!("src/{} cannot be read", module.file.display())); + return; + }; + self.visited.insert(module.file.to_path_buf()); + let source = read_source(&text); + if !test && module.depth > 0 { + self.problems + .extend(violations(module, &source.code, self.layers)); + } + for child in &source.children { + let Some(file) = child_file(self.src, module.file, own_dir, child) else { + self.problems.push(format!( + "src/{}: the file of `mod {}` was not found", + module.file.display(), + child.name + )); + continue; + }; + let (top, layer) = if module.depth == 0 { + match self.layers.get(&child.name) { + Some(layer) => (child.name.as_str(), *layer), + None => { + self.problems + .push(format!("src/lib.rs: `mod {}` has no layer", child.name)); + continue; + } + } + } else { + (module.top, module.layer) + }; + let child_module = Module { + file: &file, + top, + layer, + depth: module.depth + 1, + }; + self.module(&child_module, child.path.is_some(), test || child.test); + } + } +} + +/// Every `.rs` file under `dir`, relative to `src`. +fn rust_files(src: &Path, dir: &Path, files: &mut BTreeSet) { + let entries = fs::read_dir(src.join(dir)).expect("read a source directory"); + for entry in entries { + let name = entry.expect("read a source directory entry").file_name(); + let path = dir.join(name); + if src.join(&path).is_dir() { + rust_files(src, &path, files); + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.insert(path); + } + } +} + +/// What breaks the layering of the crate at `src`. +fn problems_of(src: &Path) -> Vec { + let lib = fs::read_to_string(src.join("lib.rs")).expect("read src/lib.rs"); + let layers = match layers_of(&lib) { + Ok(layers) => layers, + Err(problem) => return vec![problem], + }; + let mut walk = Walk { + src, + layers: &layers, + visited: BTreeSet::new(), + problems: Vec::new(), + }; + let root = Module { + file: Path::new("lib.rs"), + top: "", + layer: Layer::TestSupport, + depth: 0, + }; + walk.module(&root, true, false); + let mut files = BTreeSet::new(); + rust_files(src, Path::new(""), &mut files); + for file in files.difference(&walk.visited) { + walk.problems.push(format!( + "src/{}: no `mod` line of the crate leads to this file, so its layer is unknown", + file.display() + )); + } + walk.problems +} + +#[test] +fn every_module_stays_in_its_layer() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let problems = problems_of(&src); + assert!( + problems.is_empty(), + "skippy-receipts: {} problem(s) with the layers that src/lib.rs lists.\n\n{}\n\nMove \ + what both sides need into a shared module, or put the module under the `// Layer:` \ + comment of its layer.\n", + problems.len(), + problems.join("\n") + ); +} + +fn layers() -> BTreeMap { + let lib = "\ +// Layer: shared +pub mod wire; +// Layer: node +pub mod recorder; +// Layer: client +pub mod audit; +pub mod weights; +// Layer: test support +#[cfg(any(test, feature = \"test-support\"))] +pub mod toy_turn; +"; + layers_of(lib).expect("layers") +} + +/// What the check says of `text` as the file of a module of `top`. +fn check(top: &str, file: &str, depth: usize, text: &str) -> Vec { + let layers = layers(); + let module = Module { + file: Path::new(file), + top, + layer: layers[top], + depth, + }; + violations(&module, &read_source(text).code, &layers) +} + +#[test] +fn lib_rs_gives_every_module_a_layer() { + let layers = layers(); + assert_eq!(layers["wire"], Layer::Shared); + assert_eq!(layers["recorder"], Layer::Node); + assert_eq!(layers["weights"], Layer::Client); + assert_eq!(layers["toy_turn"], Layer::TestSupport); + let unplaced = layers_of("pub mod wire;\n// Layer: shared\n").unwrap_err(); + assert!( + unplaced.contains("`mod wire` is above the first"), + "{unplaced}" + ); + let unknown = layers_of("// Layer: server\npub mod wire;\n").unwrap_err(); + assert!(unknown.contains("names no layer"), "{unknown}"); +} + +#[test] +fn a_path_into_a_layer_a_module_may_not_use_is_found() { + let client = check("audit", "audit.rs", 1, "use crate::recorder::Recorder;\n"); + assert_eq!(client.len(), 1, "{client:?}"); + assert!( + client[0].starts_with("src/audit.rs:1: `crate::recorder`. `audit` is in the client layer") + && client[0].contains("`recorder` is in the node layer"), + "{client:?}" + ); + // in a group, in an expression, and through a macro's `$crate` + for (line, text) in [ + ( + 3, + "use crate::{\n wire::Receipt,\n recorder::{Recorder, TurnId},\n};\n", + ), + ( + 2, + "fn f() {\n let _ = crate::recorder::DEFAULT_WINDOW_BYTES;\n}\n", + ), + ( + 3, + "macro_rules! m {\n () => {\n $crate::recorder::Recorder\n };\n}\n", + ), + ] { + let found = check("audit", "audit.rs", 1, text); + assert_eq!(found.len(), 1, "{text}: {found:?}"); + let expected = format!("src/audit.rs:{line}: `crate::recorder`"); + assert!(found[0].starts_with(&expected), "{found:?}"); + } + // every direction that the rules close + assert_eq!( + check( + "recorder", + "recorder.rs", + 1, + "use crate::weights::WeightFile;\n" + ) + .len(), + 1 + ); + assert_eq!( + check("wire", "wire.rs", 1, "use crate::recorder::Recorder;\n").len(), + 1 + ); + assert_eq!( + check("wire", "wire.rs", 1, "use crate::audit::Profile;\n").len(), + 1 + ); + assert_eq!( + check("audit", "audit.rs", 1, "use crate::toy_turn::Turn;\n").len(), + 1 + ); +} + +#[test] +fn a_path_that_the_rules_allow_passes() { + for (top, text) in [ + ("wire", "use crate::wire::Receipt;\n"), + ( + "recorder", + "use crate::wire::Receipt;\nuse crate::recorder::Recorder;\n", + ), + ( + "audit", + "use crate::{wire::Receipt, weights::WeightFile};\n", + ), + ( + "toy_turn", + "use crate::recorder::Recorder;\nuse crate::audit::check_rows;\n", + ), + ] { + let found = check(top, "module.rs", 1, text); + assert!(found.is_empty(), "{top}: {found:?}"); + } +} + +#[test] +fn comments_and_test_modules_are_not_checked() { + let text = "\ +//! Opens what [`crate::recorder`] committed. +/// See [`crate::recorder::Recorder`]. +fn f() {} // unlike crate::recorder +const URL: &str = \"https://example.invalid\"; // crate::recorder + +#[cfg(test)] +mod tests { + use crate::recorder::Recorder; +} +"; + let found = check("audit", "audit.rs", 1, text); + assert!(found.is_empty(), "{found:?}"); + // a string keeps its `//`, and what follows it on the line is code + let text = "const A: &str = \"//\"; use crate::recorder::Recorder;\n"; + assert_eq!(check("audit", "audit.rs", 1, text).len(), 1); +} + +#[test] +fn a_name_that_is_no_module_or_a_path_around_the_check_is_found() { + let unknown = check("audit", "audit.rs", 1, "use crate::Recorder;\n"); + assert!( + unknown[0].contains("is not a module that src/lib.rs puts in a layer"), + "{unknown:?}" + ); + // from `audit/pairs.rs`, one `super` is `audit` and two are the crate + assert!(check("audit", "audit/pairs.rs", 2, "use super::Profile;\n").is_empty()); + let around = check( + "audit", + "audit/pairs.rs", + 2, + "use super::super::recorder::Recorder;\n", + ); + assert!( + around[0].contains("a `super::` path leaves `audit`"), + "{around:?}" + ); + assert_eq!( + check("audit", "audit.rs", 1, "use super::recorder::Recorder;\n").len(), + 1 + ); +} + +#[test] +fn a_file_declares_its_child_modules() { + let source = read_source( + "\ +mod header; +pub mod limits; +/// Small GGUF files in memory, for tests. +#[cfg(test)] +pub(crate) mod test_gguf; +#[cfg(test)] +#[path = \"recorder/tests.rs\"] +mod tests; +", + ); + let child = |name: &str, path: Option<&str>, test| ChildModule { + name: name.to_owned(), + path: path.map(str::to_owned), + test, + }; + assert_eq!( + source.children, + vec![ + child("header", None, false), + child("limits", None, false), + child("test_gguf", None, true), + child("tests", Some("recorder/tests.rs"), true), + ] + ); +} diff --git a/crates/skippy-runtime/src/chat_sampling_metadata.rs b/crates/skippy-runtime/src/chat_sampling_metadata.rs index 816ec159..5b24dd1e 100644 --- a/crates/skippy-runtime/src/chat_sampling_metadata.rs +++ b/crates/skippy-runtime/src/chat_sampling_metadata.rs @@ -72,7 +72,10 @@ impl ReasoningFields { /// is `metadata_json` and whose reasoning budget is `budget_tokens`: /// negative for no limit, `None` when the chat passes no sampling /// configuration, in which case the native side enforces no budget. -pub(crate) fn chat_sampling_metadata_for_native( +/// +/// Whoever states what a turn's sampler was built from, as a receipt +/// does, must read the metadata through this. +pub fn chat_sampling_metadata_for_native( metadata_json: &str, budget_tokens: Option, ) -> Cow<'_, str> { diff --git a/crates/skippy-runtime/src/lib.rs b/crates/skippy-runtime/src/lib.rs index 999a597f..728e0713 100644 --- a/crates/skippy-runtime/src/lib.rs +++ b/crates/skippy-runtime/src/lib.rs @@ -40,6 +40,7 @@ pub use activation::{ DecodeFrameBatchRequest, IterationBatchPhase, IterationBatchRequest, PartialBatchExecution, }; pub use capability_probe::{CapabilityReport, probe_capabilities}; +pub use chat_sampling_metadata::chat_sampling_metadata_for_native; pub use clef::{ClefModel, ClefModelInfo}; pub use config::{ FlashAttentionType, GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_I32, GGML_TYPE_Q4_0, @@ -75,7 +76,13 @@ pub use logging::{ }; pub use media::{MediaRejected, SpeechAudio, SpeechOutputFormat, SpeechSynthesisConfig}; pub use native::{ - ModelWorkload, PoolingType, StageModel, StageModelReader, SystemOneReadSlot, WorkloadInfo, + ModelWorkload, PoolingType, ReceiptAnchorRef, ReceiptAttention, ReceiptAttentionOp, + ReceiptAttentionWindow, ReceiptFlusher, ReceiptGlueInput, ReceiptGlueRequestRef, + ReceiptGlueResult, ReceiptGlueTensor, ReceiptGlueValues, ReceiptMemoryEvent, + ReceiptRecorderSink, ReceiptReplayScope, ReceiptReplayStepRef, ReceiptReplayer, + ReceiptStoredRows, ReceiptTensorView, ReceiptUbatchView, RecordedUbatch, StageIdle, StageModel, + StageModelReader, StoredRowError, SystemOneReadSlot, WorkloadInfo, receipt_runtime_source, + receipt_stored_row_error, }; pub use native_mtp::NativeMtpDraft; pub use native_test_evidence::write_evidence_marker; diff --git a/crates/skippy-runtime/src/native.rs b/crates/skippy-runtime/src/native.rs index 0d677a34..461f5663 100644 --- a/crates/skippy-runtime/src/native.rs +++ b/crates/skippy-runtime/src/native.rs @@ -15,6 +15,23 @@ use crate::path_cstring::path_to_cstring; use crate::runtime_events; use crate::session::StageSession; use crate::vocabulary::{ensure_in_vocabulary, vocabulary_size}; +mod receipt_attention; +mod receipt_glue; +mod receipts; + +pub use receipt_attention::{ + ReceiptAttention, ReceiptAttentionOp, ReceiptAttentionWindow, ReceiptStoredRows, +}; +pub use receipt_glue::{ + ReceiptGlueInput, ReceiptGlueRequestRef, ReceiptGlueResult, ReceiptGlueTensor, + ReceiptGlueValues, StoredRowError, receipt_stored_row_error, +}; +pub use receipts::{ + ReceiptAnchorRef, ReceiptFlusher, ReceiptMemoryEvent, ReceiptRecorderSink, ReceiptReplayScope, + ReceiptReplayStepRef, ReceiptReplayer, ReceiptTensorView, ReceiptUbatchView, RecordedUbatch, + StageIdle, receipt_runtime_source, +}; + use crate::{ ActivationBoundaryDesc, ChatReasoningFormat, ChatTemplateJsonOptions, ChatTemplateJsonResult, ChatTemplateMessage, ChatTemplateOptions, LoadedModelCapability, ModelOpenEventQueue, @@ -111,6 +128,7 @@ struct StageModelInner { dflash: Option, /// Target-layer capture for a split DFlash draft on a later stage. dflash_capture: Option, + receipt_recorder: receipts::InstalledRecorder, } /// A read-only model handle for vocabulary operations that do not touch a @@ -176,6 +194,7 @@ impl StageModel { capability: None, dflash: None, dflash_capture: None, + receipt_recorder: Default::default(), }), media: None, } @@ -222,6 +241,26 @@ impl StageModel { raw.try_into() } + /// The model's `.block_count`, the layer count llama.cpp counts + /// `n_gpu_layers` against, also on a stage that loads only some of the + /// layers. `None` when the model does not name one. + pub fn block_count(&self) -> Option { + if self.inner.raw.is_null() { + return None; + } + let model: *const skippy_ffi::Opaque = + unsafe { skippy_ffi::skippy_model_llama_model(self.inner.raw) }.cast(); + if model.is_null() { + return None; + } + let architecture = + unsafe { skippy_ffi::llama_model_meta_val_str(model, "general.architecture") }?; + let key = format!("{architecture}.block_count"); + unsafe { skippy_ffi::llama_model_meta_val_str(model, &key) }? + .parse() + .ok() + } + /// A loaded causal graph can read next-token scores without sampling. /// This is independent of whether this worker owns the terminal head. pub fn supports_causal_readout(&self) -> bool { @@ -246,6 +285,7 @@ impl StageModel { capability, dflash: None, dflash_capture: None, + receipt_recorder: Default::default(), }), media: None, }; diff --git a/crates/skippy-runtime/src/native/receipt_attention.rs b/crates/skippy-runtime/src/native/receipt_attention.rs new file mode 100644 index 00000000..648c7e16 --- /dev/null +++ b/crates/skippy-runtime/src/native/receipt_attention.rs @@ -0,0 +1,238 @@ +//! The attention ops a receipt replay or glue evaluation reports, and the +//! rows a stage stored in its KV cache, which the receipt attention check +//! reads and pins. + +use std::ffi::{CStr, c_void}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::ptr; + +use anyhow::{Result, anyhow, bail}; +use skippy_ffi::{ + RECEIPT_ATTENTION_CAUSAL, RECEIPT_ATTENTION_CHUNKED, RECEIPT_ATTENTION_SLIDING, ReceiptUbatch, +}; + +use super::receipts::{ReceiptReplayer, StageIdle, tensor_views}; +use crate::error::ensure_ok; + +/// Which positions an attention op's queries read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReceiptAttentionWindow { + /// Every earlier position, and its own. + Causal, + /// The last `n` positions up to its own. + Sliding(u32), + /// Earlier positions in its own chunk of `n`. + Chunked(u32), +} + +/// An attention op the check can follow, by the indices of its values +/// among the layer's reported tensors. +#[derive(Clone, Debug, PartialEq)] +pub struct ReceiptAttention { + /// q, among the layer's mixing inputs. + pub q_input: u32, + /// K and V, among the layer's stored rows. + pub k_store: u32, + pub v_store: u32, + /// The output, among the layer's mixing outputs. + pub output: u32, + /// A gate among the layer's mixing inputs that multiplies the output + /// value by value, or `None`. + pub output_gate: Option, + pub n_head: usize, + pub n_head_kv: usize, + pub head_dim_k: usize, + pub head_dim_v: usize, + pub scale: f32, + /// Zero for none. + pub softcap: f32, + pub window: ReceiptAttentionWindow, + /// A logit per query head that only adds to the softmax's denominator. + pub sinks: Option>, + /// A rotation of each head of the output in chunks of `n` values, row + /// after row, before the gate: `(n, matrix)`. + pub output_rotation: Option<(usize, Vec)>, + /// A ggml type the kernel rounds each head of q to before its dot with + /// K. + pub q_rounding: Option, +} + +/// One attention op of a reported layer, or why the check cannot follow it. +#[derive(Clone, Debug, PartialEq)] +pub struct ReceiptAttentionOp { + pub layer: u32, + pub op: std::result::Result, +} + +/// The attention ops of a native ubatch. +pub(super) unsafe fn attention_ops(u: &ReceiptUbatch) -> Result, String> { + let raw: &[skippy_ffi::ReceiptAttention] = if u.n_attention == 0 || u.attention.is_null() { + &[] + } else { + unsafe { std::slice::from_raw_parts(u.attention, u.n_attention) } + }; + raw.iter().map(|a| unsafe { attention_op(a) }).collect() +} + +unsafe fn attention_op(a: &skippy_ffi::ReceiptAttention) -> Result { + let layer = u32::try_from(a.layer).map_err(|_| "an attention op of no layer".to_string())?; + if !a.error.is_null() { + let reason = unsafe { CStr::from_ptr(a.error) } + .to_string_lossy() + .into_owned(); + return Ok(ReceiptAttentionOp { + layer, + op: Err(reason), + }); + } + let index = |i: i32| u32::try_from(i).map_err(|_| "a negative attention index".to_string()); + let count = |n: i32| usize::try_from(n).map_err(|_| "a negative attention shape".to_string()); + let size = u32::try_from(a.window).map_err(|_| "a negative attention window".to_string())?; + let window = match a.window_kind { + RECEIPT_ATTENTION_CAUSAL => ReceiptAttentionWindow::Causal, + RECEIPT_ATTENTION_SLIDING => ReceiptAttentionWindow::Sliding(size), + RECEIPT_ATTENTION_CHUNKED => ReceiptAttentionWindow::Chunked(size), + kind => return Err(format!("attention window kind {kind}")), + }; + let n_head = count(a.n_head)?; + let sinks = (!a.sinks.is_null() && n_head > 0) + .then(|| unsafe { std::slice::from_raw_parts(a.sinks, n_head) }.to_vec()); + let rotation_n = count(a.output_rotation_n)?; + let output_rotation = (rotation_n > 0 && !a.output_rotation.is_null()).then(|| { + let n = rotation_n * rotation_n; + let matrix = unsafe { std::slice::from_raw_parts(a.output_rotation, n) }; + (rotation_n, matrix.to_vec()) + }); + Ok(ReceiptAttentionOp { + layer, + op: Ok(ReceiptAttention { + q_input: index(a.q_input)?, + k_store: index(a.k_store)?, + v_store: index(a.v_store)?, + output: index(a.output)?, + output_gate: (a.output_gate >= 0) + .then(|| index(a.output_gate)) + .transpose()?, + n_head, + n_head_kv: count(a.n_head_kv)?, + head_dim_k: count(a.head_dim_k)?, + head_dim_v: count(a.head_dim_v)?, + scale: a.scale, + softcap: a.softcap, + window, + sinks, + output_rotation, + q_rounding: u32::try_from(a.q_rounding).ok(), + }), + }) +} + +/// One stored row of a layer in several KV cells, in the cache's type. +#[derive(Clone, Debug, PartialEq)] +pub struct ReceiptStoredRows { + /// Among the layer's stored rows. + pub index: u32, + pub ggml_type: i32, + pub row_bytes: usize, + /// Row `j`, for the `j`-th cell, at `values[j * row_bytes..]`. + pub values: Vec, +} + +struct RowsState { + result: Option, String>>, +} + +unsafe extern "C" fn deliver_rows(user_data: *mut c_void, ubatch: *const ReceiptUbatch) { + if user_data.is_null() || ubatch.is_null() { + return; + } + // SAFETY: user_data is the RowsState on read_rows()'s stack, and the + // ubatch is valid for the call. + let (state, u) = unsafe { (&mut *user_data.cast::(), &*ubatch) }; + // unwinding out of a callback the native side called would abort + let rows = catch_unwind(AssertUnwindSafe(|| { + unsafe { tensor_views(u) }.map(|tensors| { + tensors + .into_iter() + .map(|t| ReceiptStoredRows { + index: t.index, + ggml_type: t.ggml_type, + row_bytes: t.row_bytes, + values: t.values.to_vec(), + }) + .collect() + }) + })); + state.result = Some(rows.unwrap_or_else(|_| Err("reading the stored rows panicked".into()))); +} + +impl ReceiptReplayer { + /// The rows the stage context stored for `layer` in `cells` of the + /// stream of `seq`, from its KV cache, one entry per stored row of the + /// layer, by index. It reads the stage context's cache, which `idle` + /// keeps still. + pub fn read_rows( + &self, + idle: &StageIdle<'_>, + layer: u32, + seq: i32, + cells: &[u32], + ) -> Result> { + self.check_idle(idle)?; + let mut state = RowsState { result: None }; + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_read_receipt_rows( + self.raw(), + i32::try_from(layer)?, + seq, + cells.as_ptr(), + cells.len(), + Some(deliver_rows), + ptr::from_mut(&mut state).cast::(), + &mut error, + ) + }; + ensure_ok(status, error)?; + let mut rows = state + .result + .ok_or_else(|| anyhow!("the stage reported no rows"))? + .map_err(|reason| anyhow!("cannot read stored rows: {reason}"))?; + rows.sort_by_key(|r| r.index); + Ok(rows) + } + + /// Pins `cells` of the stage context, cell i in stream `streams[i]`, + /// replacing the cells pinned before: while one is empty, ubatches go + /// to other cells as long as they fit, so a finished turn's rows stay + /// readable for its challenge window. Safe while the stage context + /// computes. + pub fn pin_cells(&self, streams: &[u32], cells: &[u32]) -> Result<()> { + if streams.len() != cells.len() { + bail!("a pinned cell needs its stream"); + } + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_pin_receipt_cells( + self.raw(), + streams.as_ptr(), + cells.as_ptr(), + cells.len(), + &mut error, + ) + }; + ensure_ok(status, error) + } + + /// The streams of the stage context's KV cache: 1 for a unified cache, + /// else one per sequence, stream s holding the cells of sequence s. + pub fn kv_streams(&self) -> Result { + let mut streams = 0; + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_receipt_kv_streams(self.raw(), &mut streams, &mut error) + }; + ensure_ok(status, error)?; + Ok(streams) + } +} diff --git a/crates/skippy-runtime/src/native/receipt_glue.rs b/crates/skippy-runtime/src/native/receipt_glue.rs new file mode 100644 index 00000000..34473cd9 --- /dev/null +++ b/crates/skippy-runtime/src/native/receipt_glue.rs @@ -0,0 +1,319 @@ +//! Evaluates the glue of one layer on a receipt opening, the recurrent +//! token mixing of one layer, and the input of layer 0 from tokens, for an +//! auditor. + +use std::ffi::{CStr, c_void}; +use std::ptr; + +use anyhow::{Result, anyhow}; +use skippy_ffi::{ReceiptGlueRequest, ReceiptGlueValue, ReceiptUbatch}; + +use super::StageModel; +use super::receipts::tensor_views; +use crate::error::ensure_ok; + +/// Values of an opened tensor, column after column. +#[derive(Clone, Copy)] +pub enum ReceiptGlueValues<'a> { + F32(&'a [f32]), + I32(&'a [i32]), +} + +/// An opened value the evaluation uses instead of computing it. +#[derive(Clone, Copy)] +pub struct ReceiptGlueInput<'a> { + /// `RECEIPT_TENSOR_MATMUL_OUTPUT`, `_MIXING_OUTPUT` or `_SELECTION`. + pub kind: i32, + pub index: u32, + /// Elements per column. + pub len: usize, + pub values: ReceiptGlueValues<'a>, +} + +/// One layer at a few positions. +pub struct ReceiptGlueRequestRef<'a> { + pub layer: u32, + pub positions: &'a [i32], + /// Residual stream entering the layer, column after column. + pub residual: &'a [f32], + pub inputs: &'a [ReceiptGlueInput<'a>], +} + +/// A computed tensor, column after column, as F32 or I32 bytes. +#[derive(Clone, Debug)] +pub struct ReceiptGlueTensor { + pub layer: u32, + pub kind: i32, + pub index: u32, + pub ggml_type: i32, + pub flags: i32, + pub len: usize, + pub n_cols: usize, + pub name: String, + pub values: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct ReceiptGlueResult { + pub tensors: Vec, + /// Weights read inside token-mixing regions, which nothing checks. + pub unchecked_weights: Vec, + /// The attention ops of the layer. + pub attention: Vec, +} + +/// How far a stored KV row is from the row an auditor computed. +#[derive(Clone, Copy, Debug)] +pub struct StoredRowError { + /// L2 distance of the dequantized stored row from the computed row. + pub stored: f64, + /// L2 distance of the computed row from its own round trip through the cache type. + pub rounding: f64, + /// L2 norm of the computed row. + pub norm: f64, +} + +struct GlueState { + result: Option>, +} + +unsafe extern "C" fn deliver_glue(user_data: *mut c_void, ubatch: *const ReceiptUbatch) { + if user_data.is_null() || ubatch.is_null() { + return; + } + // SAFETY: user_data is the GlueState on the evaluating call's stack, and + // the ubatch is valid for the call. + let (state, u) = unsafe { (&mut *user_data.cast::(), &*ubatch) }; + state.result = Some(unsafe { collect(u) }); +} + +unsafe fn collect(u: &ReceiptUbatch) -> std::result::Result { + if !u.error.is_null() { + return Err(unsafe { CStr::from_ptr(u.error) } + .to_string_lossy() + .into_owned()); + } + let tensors = unsafe { tensor_views(u) }? + .into_iter() + .map(|t| ReceiptGlueTensor { + layer: t.layer, + kind: t.kind, + index: t.index, + ggml_type: t.ggml_type, + flags: t.flags, + len: t.len, + n_cols: t.n_cols, + name: t.name.to_owned(), + values: t.values.to_vec(), + }) + .collect(); + let names: &[*const std::ffi::c_char] = if u.n_unchecked_weights == 0 { + &[] + } else { + unsafe { std::slice::from_raw_parts(u.unchecked_weights, u.n_unchecked_weights) } + }; + let unchecked_weights = names + .iter() + .map(|&name| { + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() + }) + .collect(); + let attention = unsafe { super::receipt_attention::attention_ops(u) }?; + Ok(ReceiptGlueResult { + tensors, + unchecked_weights, + attention, + }) +} + +/// Which evaluation of opened values a request runs. +#[derive(Clone, Copy)] +enum OpenedEval { + Glue, + Region, +} + +impl OpenedEval { + fn name(self) -> &'static str { + match self { + Self::Glue => "glue", + Self::Region => "region", + } + } + + /// Columns of an input: a region takes one state, from before its + /// first position. + fn columns(self, kind: i32, n_cols: usize) -> usize { + match self { + Self::Region if kind == skippy_ffi::RECEIPT_TENSOR_MIXING_STATE => 1, + _ => n_cols, + } + } +} + +impl StageModel { + /// Computes one layer of this model on opened receipt values: every + /// weight matmul, token-mixing output and selection takes the given + /// value, so the layer's large weights are not read. + pub fn eval_receipt_glue( + &self, + request: &ReceiptGlueRequestRef<'_>, + ) -> Result { + self.eval_opened(request, OpenedEval::Glue) + } + + /// Computes the recurrent token mixing of one layer from its opened + /// inputs at consecutive positions of one sequence and the opened + /// states before the first of them (one column each). The result holds + /// the mixing outputs and the states the layer leaves. + pub fn eval_receipt_region( + &self, + request: &ReceiptGlueRequestRef<'_>, + ) -> Result { + self.eval_opened(request, OpenedEval::Region) + } + + fn eval_opened( + &self, + request: &ReceiptGlueRequestRef<'_>, + eval: OpenedEval, + ) -> Result { + let n_cols = request.positions.len(); + if n_cols == 0 || !request.residual.len().is_multiple_of(n_cols) { + return Err(anyhow!( + "a {} evaluation needs a residual column per position", + eval.name() + )); + } + let values = request + .inputs + .iter() + .map(|input| { + let (ggml_type, values, count) = match input.values { + ReceiptGlueValues::F32(v) => (0, v.as_ptr().cast::(), v.len()), + ReceiptGlueValues::I32(v) => (26, v.as_ptr().cast::(), v.len()), + }; + let columns = eval.columns(input.kind, n_cols); + if count != input.len * columns { + return Err(anyhow!( + "{} input {}:{} has {count} values, not {columns} columns of {}", + eval.name(), + input.kind, + input.index, + input.len + )); + } + Ok(ReceiptGlueValue { + kind: input.kind, + index: i32::try_from(input.index)?, + ggml_type, + len: i64::try_from(input.len)?, + values, + }) + }) + .collect::>>()?; + let raw = ReceiptGlueRequest { + layer: i32::try_from(request.layer)?, + n_cols: i32::try_from(n_cols)?, + pos: request.positions.as_ptr(), + residual: request.residual.as_ptr(), + residual_len: i64::try_from(request.residual.len() / n_cols)?, + n_values: values.len(), + values: values.as_ptr(), + }; + let mut state = GlueState { result: None }; + let mut error = ptr::null_mut(); + let user_data = ptr::from_mut(&mut state).cast::(); + let status = unsafe { + match eval { + OpenedEval::Glue => skippy_ffi::skippy_model_eval_receipt_glue( + self.inner.raw, + &raw, + Some(deliver_glue), + user_data, + &mut error, + ), + OpenedEval::Region => skippy_ffi::skippy_model_eval_receipt_region( + self.inner.raw, + &raw, + Some(deliver_glue), + user_data, + &mut error, + ), + } + }; + ensure_ok(status, error)?; + match state.result { + Some(Ok(result)) => Ok(result), + Some(Err(reason)) => Err(anyhow!("the layer cannot be evaluated: {reason}")), + None => Err(anyhow!("the {} evaluation reported nothing", eval.name())), + } + } + + /// Computes the residual entering layer 0 for each token at its + /// position. The model must hold layer 0. The result holds one RESIDUAL + /// tensor of layer 0, a column per token. + pub fn eval_receipt_entry( + &self, + tokens: &[i32], + positions: &[i32], + ) -> Result { + if tokens.is_empty() || tokens.len() != positions.len() { + return Err(anyhow!("an entry evaluation needs a position per token")); + } + let mut state = GlueState { result: None }; + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_eval_receipt_entry( + self.inner.raw, + tokens.as_ptr(), + positions.as_ptr(), + i32::try_from(tokens.len())?, + Some(deliver_glue), + ptr::from_mut(&mut state).cast::(), + &mut error, + ) + }; + ensure_ok(status, error)?; + match state.result { + Some(Ok(result)) => Ok(result), + Some(Err(reason)) => Err(anyhow!( + "the input of layer 0 cannot be evaluated: {reason}" + )), + None => Err(anyhow!("the entry evaluation reported nothing")), + } + } +} + +/// Compares a stored KV row with the f32 row an auditor computed. The +/// stored bytes and their type come from the opening, so the runtime reads +/// them only when they are one whole row of that type. +pub fn receipt_stored_row_error( + ggml_type: i32, + stored: &[u8], + computed: &[f32], +) -> Result { + let mut out = StoredRowError { + stored: 0.0, + rounding: 0.0, + norm: 0.0, + }; + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_receipt_stored_row_error( + ggml_type, + stored.as_ptr().cast::(), + stored.len(), + computed.as_ptr(), + i64::try_from(computed.len())?, + &mut out.stored, + &mut out.rounding, + &mut out.norm, + &mut error, + ) + }; + ensure_ok(status, error)?; + Ok(out) +} diff --git a/crates/skippy-runtime/src/native/receipts.rs b/crates/skippy-runtime/src/native/receipts.rs new file mode 100644 index 00000000..60b8fcfe --- /dev/null +++ b/crates/skippy-runtime/src/native/receipts.rs @@ -0,0 +1,890 @@ +//! Delivers the native receipt recorder to a Rust sink, and replays a +//! recorded sequence to open a receipt challenge. + +use std::ffi::{CStr, c_void}; +use std::marker::PhantomData; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::ptr; +use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak}; + +use anyhow::{Result, anyhow, bail}; +use skippy_ffi::{ReceiptAnchor, ReceiptReplayStep, ReceiptTensor, ReceiptUbatch}; + +use super::{StageModel, StageModelInner}; + +use crate::error::ensure_ok; +pub use skippy_ffi::ReceiptMemoryEvent; + +/// One reported tensor, column per token (or per output row). +#[derive(Clone, Copy)] +pub struct ReceiptTensorView<'a> { + pub layer: u32, + /// A `skippy_ffi::RECEIPT_TENSOR_*` kind. + pub kind: i32, + /// Ordinal among the layer's tensors of this kind. + pub index: u32, + /// ggml type of the values: F32, I32, or a stored row's cache type. + pub ggml_type: i32, + /// `skippy_ffi::RECEIPT_TENSOR_ROUTER` and other flags. + pub flags: i32, + /// Elements per column. + pub len: usize, + pub row_bytes: usize, + pub n_cols: usize, + /// Column `j` at `values[j * row_bytes..]`; empty when the recorder + /// reported digests instead. + pub values: &'a [u8], + /// Per column, the BLAKE3 digest of its `row_bytes` bytes, when the + /// recorder computed it where the values are; empty otherwise. + pub digests: &'a [[u8; 32]], + /// The weight's name for a matmul, else the graph node's name. Empty in + /// a [`RecordedUbatch`], which keeps no names: a served ubatch commits + /// values, and only a replay names the weights it opens. + pub name: &'a str, +} + +impl<'a> ReceiptTensorView<'a> { + /// Column `j` as raw bytes; empty when only its digest was reported. + pub fn column(&self, j: usize) -> &'a [u8] { + self.values + .get(j * self.row_bytes..(j + 1) * self.row_bytes) + .unwrap_or(&[]) + } + + /// The digest of column `j`, when the recorder reported digests. + pub fn column_digest(&self, j: usize) -> Option<[u8; 32]> { + self.digests.get(j).copied() + } +} + +/// One computed ubatch, borrowed for the duration of the callback. +pub struct ReceiptUbatchView<'a> { + /// Replay step index, or `None` while serving. + pub step: Option, + pub token: &'a [i32], + pub seq: &'a [i32], + pub pos: &'a [i32], + pub output: &'a [i8], + pub cell: &'a [u32], + pub n_kv: u32, + /// Stage input rows and their ggml type, for a stage after the first. + pub input: Option<(&'a [u8], usize, i32)>, + pub tensors: Vec>, + /// Replay: the attention ops of the reported layers. + pub attention: Vec, +} + +/// Receives the recorder's reports, in order: on the decoding thread, or on a +/// thread that calls [`ReceiptFlusher::flush`]. +pub trait ReceiptRecorderSink: Send + Sync { + /// A computed ubatch. It can be kept and read on any thread, but the next + /// ubatch is not delivered until it is dropped: decoding waits for it. + fn ubatch(&self, ubatch: RecordedUbatch); + /// The recorder lost track of the stage: a report it could not take. + fn unreceiptable(&self, reason: &str); + /// The stage computed a ubatch the recorder could not receipt, such as + /// one of embeddings. The report names neither its sequences nor its + /// cells. + fn unrecorded_ubatch(&self, reason: &str) { + self.unreceiptable(reason); + } + fn memory(&self, event: &ReceiptMemoryEvent); + /// The recurrent state a sequence's next turn starts from, on a model + /// with hybrid memory; `None` when it could not be read. Decoding waits + /// for the call. + fn state(&self, seq: i32, state: Option<&[u8]>) { + let _ = (seq, state); + } +} + +/// Whether a delivered ubatch still borrows the native tensor buffers. +#[derive(Default)] +struct ReleaseGate { + held: Mutex, + released: Condvar, +} + +impl ReleaseGate { + fn hold(&self) { + *self.held.lock().unwrap_or_else(PoisonError::into_inner) = true; + } + + fn release(&self) { + *self.held.lock().unwrap_or_else(PoisonError::into_inner) = false; + self.released.notify_all(); + } + + fn wait_released(&self) { + let held = self.held.lock().unwrap_or_else(PoisonError::into_inner); + drop( + self.released + .wait_while(held, |held| *held) + .unwrap_or_else(PoisonError::into_inner), + ); + } +} + +/// What the native recorder's user data points at. +struct RecorderBinding { + sink: Arc, + model: Weak, + gate: Arc, +} + +/// Keeps the sink alive while the native recorder points at it. +#[derive(Default)] +pub(super) struct InstalledRecorder(Mutex>>); + +struct RecordedTensor { + layer: u32, + kind: i32, + index: u32, + ggml_type: i32, + flags: i32, + len: usize, + row_bytes: usize, + n_cols: usize, + // pointer and length of the values, and of the digests + values: (*const u8, usize), + digests: (*const [u8; 32], usize), +} + +/// One computed ubatch, owned. The native recorder keeps the tensor values +/// of a ubatch until the callback for the next ubatch returns, and the +/// runtime does not deliver the next ubatch until this is dropped, so the +/// values stay valid for its lifetime. It keeps the model alive. +pub struct RecordedUbatch { + pub token: Vec, + pub seq: Vec, + pub pos: Vec, + pub output: Vec, + pub cell: Vec, + pub n_kv: u32, + /// Stage input rows, row size in bytes, and ggml type. + pub input: Option<(Vec, usize, i32)>, + tensors: Vec, + gate: Arc, + _model: Arc, +} + +// SAFETY: the tensor pointers are read-only and stay valid until drop (see +// the type docs); everything else is owned. +unsafe impl Send for RecordedUbatch {} +unsafe impl Sync for RecordedUbatch {} + +impl RecordedUbatch { + fn new( + view: &ReceiptUbatchView<'_>, + gate: Arc, + model: Arc, + ) -> Self { + gate.hold(); + Self { + token: view.token.to_vec(), + seq: view.seq.to_vec(), + pos: view.pos.to_vec(), + output: view.output.to_vec(), + cell: view.cell.to_vec(), + n_kv: view.n_kv, + input: view + .input + .map(|(rows, row, ggml_type)| (rows.to_vec(), row, ggml_type)), + tensors: view + .tensors + .iter() + .map(|t| RecordedTensor { + layer: t.layer, + kind: t.kind, + index: t.index, + ggml_type: t.ggml_type, + flags: t.flags, + len: t.len, + row_bytes: t.row_bytes, + n_cols: t.n_cols, + values: (t.values.as_ptr(), t.values.len()), + digests: (t.digests.as_ptr(), t.digests.len()), + }) + .collect(), + gate, + _model: model, + } + } + + /// The reported tensors, without their names: the native names live in + /// the graph, which the next ubatch may rebuild, and copying one per + /// tensor would allocate on the decoding thread for nothing a served + /// ubatch commits. + pub fn tensors(&self) -> impl Iterator> { + self.tensors.iter().map(|t| ReceiptTensorView { + layer: t.layer, + kind: t.kind, + index: t.index, + ggml_type: t.ggml_type, + flags: t.flags, + len: t.len, + row_bytes: t.row_bytes, + n_cols: t.n_cols, + // SAFETY: valid until self is dropped, see the type docs. + values: unsafe { std::slice::from_raw_parts(t.values.0, t.values.1) }, + digests: unsafe { std::slice::from_raw_parts(t.digests.0, t.digests.1) }, + name: "", + }) + } +} + +impl Drop for RecordedUbatch { + fn drop(&mut self) { + self.gate.release(); + } +} + +/// Safe views of the tensors of a native ubatch. +pub(super) unsafe fn tensor_views<'a>( + u: &'a ReceiptUbatch, +) -> Result>, String> { + let raw: &[ReceiptTensor] = if u.n_tensors == 0 { + &[] + } else { + unsafe { std::slice::from_raw_parts(u.tensors, u.n_tensors) } + }; + let mut tensors = Vec::with_capacity(raw.len()); + for t in raw { + let (Ok(layer), Ok(index), Ok(len), Ok(row_bytes), Ok(n_cols)) = ( + u32::try_from(t.layer), + u32::try_from(t.index), + usize::try_from(t.len), + usize::try_from(t.row_bytes), + usize::try_from(t.n_cols), + ) else { + return Err("malformed receipt tensor".to_string()); + }; + let name = if t.name.is_null() { + "" + } else { + unsafe { CStr::from_ptr(t.name) }.to_str().unwrap_or("") + }; + tensors.push(ReceiptTensorView { + layer, + kind: t.kind, + index, + ggml_type: t.ggml_type, + flags: t.flags, + len, + row_bytes, + n_cols, + values: if t.values.is_null() || row_bytes * n_cols == 0 { + &[] + } else { + unsafe { std::slice::from_raw_parts(t.values.cast::(), row_bytes * n_cols) } + }, + digests: if t.digests.is_null() || n_cols == 0 { + &[] + } else { + unsafe { std::slice::from_raw_parts(t.digests.cast::<[u8; 32]>(), n_cols) } + }, + name, + }); + } + Ok(tensors) +} + +/// `n` values at `pointer`, or `Err` when the native side reported columns +/// but no values for them. A null or dangling pointer with no column is an +/// empty slice. +unsafe fn columns<'a, T>(pointer: *const T, n: usize, what: &str) -> Result<&'a [T], String> { + if n == 0 { + return Ok(&[]); + } + if pointer.is_null() { + return Err(format!("the ubatch reports {n} tokens and no {what}")); + } + // SAFETY: the native side holds `n` values at a non-null pointer for the + // call. + Ok(unsafe { std::slice::from_raw_parts(pointer, n) }) +} + +/// Builds a safe view of a native ubatch; `Err` carries the native reason +/// the ubatch cannot be receipted. +unsafe fn view<'a>(u: &'a ReceiptUbatch) -> Result, String> { + if !u.error.is_null() { + return Err(unsafe { CStr::from_ptr(u.error) } + .to_string_lossy() + .into_owned()); + } + let n = usize::try_from(u.n_tokens).map_err(|_| "negative token count".to_string())?; + let input = if u.input.is_null() { + None + } else { + let row = usize::try_from(u.input_row_bytes).map_err(|_| "bad input row".to_string())?; + let bytes = row + .checked_mul(n) + .ok_or_else(|| "input rows overflow".to_string())?; + Some(( + unsafe { columns(u.input.cast::(), bytes, "input rows") }?, + row, + u.input_type, + )) + }; + let tensors = unsafe { tensor_views(u) }?; + let attention = unsafe { super::receipt_attention::attention_ops(u) }?; + Ok(ReceiptUbatchView { + step: usize::try_from(u.step).ok(), + token: unsafe { columns(u.token, n, "token ids") }?, + seq: unsafe { columns(u.seq, n, "sequences") }?, + pos: unsafe { columns(u.pos, n, "positions") }?, + output: unsafe { columns(u.output, n, "output flags") }?, + cell: unsafe { columns(u.cell, n, "cells") }?, + n_kv: u.n_kv, + input, + tensors, + attention, + }) +} + +/// Runs a recorder report, and turns a panic in it into an unreceiptable +/// report: unwinding out of a callback the native side called would abort +/// the process. +fn deliver(binding: &RecorderBinding, what: &str, report: impl FnOnce()) { + if catch_unwind(AssertUnwindSafe(report)).is_ok() { + return; + } + let reason = format!("the receipt recorder panicked on {what}"); + // the sink that panicked may panic again + let _ = catch_unwind(AssertUnwindSafe(|| binding.sink.unreceiptable(&reason))); +} + +unsafe extern "C" fn deliver_ubatch(user_data: *mut c_void, ubatch: *const ReceiptUbatch) { + if user_data.is_null() || ubatch.is_null() { + return; + } + // SAFETY: user_data is the binding owned by InstalledRecorder, and the + // native side keeps the ubatch buffers alive for the call. + let binding = unsafe { &*user_data.cast::() }; + deliver(binding, "a ubatch", || { + // Once this returns, the native side may overwrite the previous + // ubatch's buffers. + binding.gate.wait_released(); + let Some(model) = binding.model.upgrade() else { + binding.sink.unreceiptable("the model is being freed"); + return; + }; + match unsafe { view(&*ubatch) } { + Ok(view) => { + binding + .sink + .ubatch(RecordedUbatch::new(&view, binding.gate.clone(), model)) + } + Err(reason) => binding.sink.unrecorded_ubatch(&reason), + } + }); +} + +unsafe extern "C" fn deliver_memory(user_data: *mut c_void, event: *const ReceiptMemoryEvent) { + if user_data.is_null() || event.is_null() { + return; + } + // SAFETY: as in deliver_ubatch. + let (binding, event) = unsafe { (&*user_data.cast::(), &*event) }; + deliver(binding, "a KV-cache event", || binding.sink.memory(event)); +} + +unsafe extern "C" fn deliver_state( + user_data: *mut c_void, + seq: i32, + bytes: *const c_void, + n_bytes: usize, +) { + if user_data.is_null() { + return; + } + // SAFETY: as in deliver_ubatch; the native side keeps `bytes` alive for + // the call. + let binding = unsafe { &*user_data.cast::() }; + let state = (!bytes.is_null() && n_bytes > 0) + .then(|| unsafe { std::slice::from_raw_parts(bytes.cast::(), n_bytes) }); + deliver(binding, "a recurrent state", || { + binding.sink.state(seq, state); + }); +} + +/// One step of a receipt replay. +pub enum ReceiptReplayStepRef<'a> { + Decode { + token: &'a [i32], + seq: &'a [i32], + pos: &'a [i32], + output: &'a [i8], + cell: &'a [u32], + n_kv: u32, + /// Stage input rows, row size in bytes, and ggml type. + input: Option<(&'a [u8], usize, i32)>, + capture: bool, + }, + /// Removes positions `[p0, p1)` of the replayed sequence; `p1 < 0` has no end. + SeqRm { p0: i32, p1: i32 }, +} + +/// A committed value an anchored replay writes into one token's column. +pub struct ReceiptAnchorRef<'a> { + /// The decode step, as an index into the replay's steps. + pub step: usize, + pub seq: i32, + pub pos: i32, + pub layer: u32, + /// `RECEIPT_TENSOR_RESIDUAL`, the residual entering `layer`, or + /// `RECEIPT_TENSOR_MIXING_OUTPUT`. + pub kind: i32, + pub index: u32, + pub values: &'a [f32], +} + +/// Which tensors a replay reports, and from which values. +pub enum ReceiptReplayScope<'a> { + /// The committed tensors, the matmuls and the selections. + Full, + /// Only the tensors the live recorder marks, so a backend fuses its + /// kernels as it did live; no matmuls or selections. + Committed, + /// As [`Self::Full`], with the anchors' values written into their + /// tokens' columns as soon as they are computed. + Anchored(&'a [ReceiptAnchorRef<'a>]), +} + +/// Replays recorded sequences in the model's scratch context. Cheap to clone +/// and usable from any thread; it keeps the model alive. What reads the +/// stage context itself ([`Self::seed`], [`Self::seed_state`], +/// [`Self::read_rows`]) takes a [`StageIdle`]. +#[derive(Clone)] +pub struct ReceiptReplayer { + inner: Arc, +} + +/// Proof that a stage context is idle: while it lives, no decode and no +/// memory operation runs on the context. It borrows the [`StageModel`] +/// exclusively, and a serving stage reaches its model, and decodes on it, +/// only inside its runtime lock, so holding one means holding that lock. +pub struct StageIdle<'a> { + raw: *mut skippy_ffi::Model, + _stage: PhantomData<&'a mut StageModel>, +} + +struct CaptureState<'f> { + on_capture: &'f mut dyn FnMut(&ReceiptUbatchView<'_>) -> Result<()>, + error: Option, +} + +unsafe extern "C" fn deliver_capture(user_data: *mut c_void, ubatch: *const ReceiptUbatch) { + if user_data.is_null() || ubatch.is_null() { + return; + } + // SAFETY: user_data is the CaptureState on replay()'s stack. + let state = unsafe { &mut *user_data.cast::>() }; + if state.error.is_some() { + return; + } + // unwinding out of a callback the native side called would abort + let result = catch_unwind(AssertUnwindSafe(|| match unsafe { view(&*ubatch) } { + Ok(view) => (state.on_capture)(&view), + Err(reason) => Err(anyhow!("replay cannot capture: {reason}")), + })) + .unwrap_or_else(|_| Err(anyhow!("reading a replayed ubatch panicked"))); + if let Err(error) = result { + state.error = Some(error); + } +} + +impl ReceiptReplayer { + pub(super) fn raw(&self) -> *mut skippy_ffi::Model { + self.inner.raw + } + + /// Replays `seq` and calls `on_capture` for every captured step, which + /// reports each of the sorted `layers` as `scope` says. + pub fn replay( + &self, + seq: i32, + layers: &[u32], + scope: &ReceiptReplayScope<'_>, + steps: &[ReceiptReplayStepRef<'_>], + on_capture: &mut dyn FnMut(&ReceiptUbatchView<'_>) -> Result<()>, + ) -> Result<()> { + let raw_steps = steps.iter().map(raw_step).collect::>>()?; + let layers = layers + .iter() + .map(|&layer| i32::try_from(layer)) + .collect::, _>>()?; + let mut state = CaptureState { + on_capture, + error: None, + }; + let mut error = ptr::null_mut(); + let user_data = ptr::from_mut(&mut state).cast::(); + let (model, steps) = (self.inner.raw, raw_steps.as_ptr()); + let (n_layers, n_steps, layers) = (layers.len(), raw_steps.len(), layers.as_ptr()); + let on_capture: skippy_ffi::ReceiptUbatchFn = Some(deliver_capture); + let status = match scope { + ReceiptReplayScope::Full => unsafe { + skippy_ffi::skippy_model_replay_receipt( + model, seq, layers, n_layers, steps, n_steps, on_capture, user_data, &mut error, + ) + }, + ReceiptReplayScope::Committed => unsafe { + skippy_ffi::skippy_model_replay_receipt_committed( + model, seq, layers, n_layers, steps, n_steps, on_capture, user_data, &mut error, + ) + }, + ReceiptReplayScope::Anchored(anchors) => { + let anchors = anchors.iter().map(raw_anchor).collect::>>()?; + unsafe { + skippy_ffi::skippy_model_replay_receipt_anchored( + model, + seq, + layers, + n_layers, + steps, + n_steps, + anchors.as_ptr(), + anchors.len(), + on_capture, + user_data, + &mut error, + ) + } + } + }; + ensure_ok(status, error)?; + state.error.map_or(Ok(()), Err) + } + + /// Fails unless `idle` is this replayer's stage context. + pub(super) fn check_idle(&self, idle: &StageIdle<'_>) -> Result<()> { + if idle.raw != self.inner.raw { + bail!("the idle stage context is not the one the replayer reads"); + } + Ok(()) + } + + /// Seeds the next replay of `seq` with the stage context's `cells`, which + /// must hold positions `pos` (of any sequence); they become positions of + /// `seq` in the scratch context, which is made to hold `n_cells` cells. + /// It reads the stage context's cache, which `idle` keeps still. + pub fn seed( + &self, + idle: &StageIdle<'_>, + seq: i32, + cells: &[u32], + pos: &[i32], + n_cells: u32, + ) -> Result<()> { + self.check_idle(idle)?; + if cells.len() != pos.len() { + bail!("a seeded cell needs a position"); + } + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_seed_receipt_replay( + self.inner.raw, + seq, + cells.as_ptr(), + pos.as_ptr(), + cells.len(), + n_cells, + &mut error, + ) + }; + ensure_ok(status, error) + } + + /// Imports the recurrent state a turn started from into `seq` of the + /// scratch context, after [`Self::seed`] copied its KV cells, under the + /// same `idle`: a replay of another turn must not take the seeded cells + /// in between. + pub fn seed_state(&self, idle: &StageIdle<'_>, seq: i32, state: &[u8]) -> Result<()> { + self.check_idle(idle)?; + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_seed_receipt_state( + self.inner.raw, + seq, + state.as_ptr().cast::(), + state.len(), + &mut error, + ) + }; + ensure_ok(status, error) + } + + /// Frees the scratch context; the next replay creates it again. A + /// running replay keeps it. + pub fn release_scratch(&self) -> Result<()> { + let mut error = ptr::null_mut(); + let status = + unsafe { skippy_ffi::skippy_model_release_receipt_scratch(self.inner.raw, &mut error) }; + ensure_ok(status, error) + } +} + +/// Reports the ubatches the receipt recorder holds back: a device that copies +/// asynchronously reports a ubatch two ubatches late, or before the next +/// memory event. Call [`ReceiptFlusher::flush`] before reading what the sink +/// received. +#[derive(Clone)] +pub struct ReceiptFlusher { + inner: Weak, +} + +impl ReceiptFlusher { + /// Delivers the held-back ubatches, if any, to the sink on this thread. + /// A freed model has nothing held back. + pub fn flush(&self) -> Result<()> { + let Some(inner) = self.inner.upgrade() else { + return Ok(()); + }; + let mut error = ptr::null_mut(); + let status = + unsafe { skippy_ffi::skippy_model_flush_receipt_recorder(inner.raw, &mut error) }; + ensure_ok(status, error) + } + + /// Starts a new turn of `seq`: on a model with hybrid memory, its next + /// ubatch reports its recurrent state first. + pub fn arm_state(&self, seq: i32) -> Result<()> { + let Some(inner) = self.inner.upgrade() else { + return Ok(()); + }; + let mut error = ptr::null_mut(); + let status = + unsafe { skippy_ffi::skippy_model_arm_receipt_state(inner.raw, seq, &mut error) }; + ensure_ok(status, error) + } +} + +fn raw_anchor(anchor: &ReceiptAnchorRef<'_>) -> Result { + Ok(ReceiptAnchor { + step: anchor.step, + seq: anchor.seq, + pos: anchor.pos, + layer: i32::try_from(anchor.layer)?, + kind: anchor.kind, + index: i32::try_from(anchor.index)?, + len: i64::try_from(anchor.values.len())?, + values: anchor.values.as_ptr(), + }) +} + +fn raw_step(step: &ReceiptReplayStepRef<'_>) -> Result { + Ok(match *step { + ReceiptReplayStepRef::Decode { + token, + seq, + pos, + output, + cell, + n_kv, + input, + capture, + } => { + let n = token.len(); + if [seq.len(), pos.len(), output.len(), cell.len()] + .iter() + .any(|&len| len != n) + || input.is_some_and(|(rows, row, _)| rows.len() != row * n) + { + return Err(anyhow!("replay step columns disagree in length")); + } + let (input, row, input_type) = input.map_or((ptr::null(), 0, 0), |(rows, row, t)| { + (rows.as_ptr().cast::(), row, t) + }); + ReceiptReplayStep { + kind: skippy_ffi::RECEIPT_REPLAY_DECODE, + n_tokens: i32::try_from(n)?, + token: token.as_ptr(), + seq: seq.as_ptr(), + pos: pos.as_ptr(), + output: output.as_ptr(), + cell: cell.as_ptr(), + n_kv, + input, + input_row_bytes: i64::try_from(row)?, + input_type, + p0: 0, + p1: 0, + capture: i32::from(capture), + } + } + ReceiptReplayStepRef::SeqRm { p0, p1 } => ReceiptReplayStep { + kind: skippy_ffi::RECEIPT_REPLAY_SEQ_RM, + n_tokens: 0, + token: ptr::null(), + seq: ptr::null(), + pos: ptr::null(), + output: ptr::null(), + cell: ptr::null(), + n_kv: 0, + input: ptr::null(), + input_row_bytes: 0, + input_type: 0, + p0, + p1, + capture: 0, + }, + }) +} + +impl StageModel { + /// Reports every later ubatch and KV-cache change to `sink`, for + /// receipts. Returns whether the model has hybrid memory, whose turns + /// also report the recurrent state they start from. + pub fn set_receipt_recorder(&self, sink: Arc) -> Result { + if self.inner.raw.is_null() { + return Err(anyhow!("receipt recorder needs a loaded model")); + } + let mut slot = self + .inner + .receipt_recorder + .0 + .lock() + .map_err(|_| anyhow!("receipt recorder lock poisoned"))?; + if let Some(old) = slot.as_ref() { + // the native side frees the old recorder's buffers + old.gate.wait_released(); + } + let boxed = Box::new(RecorderBinding { + sink, + model: Arc::downgrade(&self.inner), + gate: Arc::default(), + }); + let user_data = ptr::from_ref::(&*boxed) + .cast_mut() + .cast::(); + let mut error = ptr::null_mut(); + let status = unsafe { + skippy_ffi::skippy_model_set_receipt_recorder( + self.inner.raw, + Some(deliver_ubatch), + Some(deliver_memory), + user_data, + &mut error, + ) + }; + ensure_ok(status, error)?; + let mut recurrent = false; + let status = unsafe { + skippy_ffi::skippy_model_set_receipt_state_observer( + self.inner.raw, + Some(deliver_state), + user_data, + &mut recurrent, + &mut error, + ) + }; + ensure_ok(status, error)?; + *slot = Some(boxed); + Ok(recurrent) + } + + /// Proof for a [`ReceiptReplayer`] that this model's stage context is + /// idle, for as long as the model stays borrowed. + pub fn idle(&mut self) -> StageIdle<'_> { + StageIdle { + raw: self.inner.raw, + _stage: PhantomData, + } + } + + /// A handle that replays recorded sequences of this model. + pub fn receipt_replayer(&self) -> ReceiptReplayer { + ReceiptReplayer { + inner: self.inner.clone(), + } + } + + /// A handle that reports the recorder's held-back ubatches before the + /// recorder is read. It does not keep the model alive. + pub fn receipt_flusher(&self) -> ReceiptFlusher { + ReceiptFlusher { + inner: Arc::downgrade(&self.inner), + } + } +} + +/// The llama.cpp commit and patch queue the native runtime was built from, +/// as its receipts name them, or `unknown`. +pub fn receipt_runtime_source() -> String { + let source = unsafe { skippy_ffi::skippy_receipt_runtime_source() }; + if source.is_null() { + return "unknown".to_owned(); + } + unsafe { CStr::from_ptr(source) } + .to_string_lossy() + .into_owned() +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + /// Panics on every report but an unreceiptable one, which it counts. + #[derive(Default)] + struct PanickingSink(AtomicUsize); + + impl ReceiptRecorderSink for PanickingSink { + fn ubatch(&self, _ubatch: RecordedUbatch) { + panic!("a ubatch"); + } + + fn unreceiptable(&self, _reason: &str) { + self.0.fetch_add(1, Ordering::SeqCst); + } + + fn memory(&self, _event: &ReceiptMemoryEvent) { + panic!("a memory event"); + } + + fn state(&self, _seq: i32, _state: Option<&[u8]>) { + panic!("a state"); + } + } + + // A panic in a sink must not unwind into the native caller, which would + // abort the process: the report becomes an unreceiptable one. + #[test] + fn a_panicking_sink_does_not_unwind_into_the_native_caller() { + let sink = Arc::new(PanickingSink::default()); + let binding = RecorderBinding { + sink: sink.clone(), + model: Weak::new(), + gate: Arc::default(), + }; + let user_data = ptr::from_ref(&binding).cast_mut().cast::(); + let event = ReceiptMemoryEvent { + op: 1, + seq: 0, + seq_dst: -1, + p0: -1, + p1: -1, + }; + unsafe { deliver_memory(user_data, &event) }; + assert_eq!(sink.0.load(Ordering::SeqCst), 1); + unsafe { deliver_state(user_data, 0, ptr::null(), 0) }; + assert_eq!(sink.0.load(Ordering::SeqCst), 2); + } + + // The native side may report a ubatch of no tokens with null columns, + // and must not report tokens without them. + #[test] + fn a_ubatch_view_takes_no_slice_of_a_null_column() { + // SAFETY: an all-zero ubatch is one of no tokens, tensors or error. + let mut ubatch: ReceiptUbatch = unsafe { std::mem::zeroed() }; + ubatch.step = -1; + let empty = unsafe { view(&ubatch) }.expect("an empty ubatch"); + assert!(empty.token.is_empty() && empty.cell.is_empty() && empty.input.is_none()); + ubatch.n_tokens = 3; + let error = unsafe { view(&ubatch) } + .err() + .expect("tokens without columns"); + assert!(error.contains("no token ids"), "{error}"); + } +} diff --git a/crates/skippy-runtime/src/types.rs b/crates/skippy-runtime/src/types.rs index efdfbfb1..404edf0b 100644 --- a/crates/skippy-runtime/src/types.rs +++ b/crates/skippy-runtime/src/types.rs @@ -705,6 +705,10 @@ pub struct SamplingConfig { /// (OpenAI `logprobs` / `top_logprobs`), read back with /// `StageSession::take_token_logprobs`. `None` records nothing. pub top_logprobs: Option, + /// Draw each sampled token with a uniform derived from `seed` and the + /// token's position, over the kept candidates in token id order, so a + /// client that holds the turn's inference receipt can replay the draw. + pub indexed_draw: bool, } /// Reasoning-token limit resolved after the prompt establishes the effective @@ -807,6 +811,7 @@ impl Default for SamplingConfig { ], reasoning_budget: ReasoningBudget::Unrestricted, top_logprobs: None, + indexed_draw: false, } } } @@ -898,6 +903,11 @@ impl SamplingConfig { skippy_ffi::SAMPLING_FLAG_LOGPROBS } else { 0 + } + | if self.indexed_draw { + skippy_ffi::SAMPLING_FLAG_INDEXED_DRAW + } else { + 0 }, seed: self.seed, top_k: self.top_k, diff --git a/crates/skippy-serving/Cargo.toml b/crates/skippy-serving/Cargo.toml index 42e6a468..3d7c2773 100644 --- a/crates/skippy-serving/Cargo.toml +++ b/crates/skippy-serving/Cargo.toml @@ -27,7 +27,10 @@ async-trait = "0.1" axum = "0.8" base64 = "0.23" blake3.workspace = true +ed25519-dalek = "=3.0.0" futures-util = "0.3" +hex = "0.4" +rand = "0.10" skippy-runtime = { path = "../skippy-runtime", version = "0.80.0" } skippy-package-format = { path = "../skippy-package-format", version = "0.80.0" } skippy-scheduler = { path = "../skippy-scheduler", version = "0.80.0" } @@ -36,10 +39,12 @@ skippy-model-artifact = { path = "../skippy-model-artifact", version = "0.80.0" skippy-events = { path = "../skippy-events", version = "0.80.0" } skippy-hardware-profile = { path = "../skippy-hardware-profile", version = "0.80.0" } skippy-protocol = { path = "../skippy-protocol", version = "0.80.0" } +skippy-receipts = { path = "../skippy-receipts", version = "0.80.0" } skippy-cache = { path = "../skippy-cache", version = "0.80.0" } skippy-metrics = { path = "../skippy-metrics", version = "0.80.0" } skippy-inference-api = { path = "../skippy-inference-api", version = "0.80.0" } opentelemetry-proto = "0.32.0" +reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "rustls"] } serde.workspace = true serde_json.workspace = true sha2.workspace = true diff --git a/crates/skippy-serving/README.md b/crates/skippy-serving/README.md index 53fad059..90c30671 100644 --- a/crates/skippy-serving/README.md +++ b/crates/skippy-serving/README.md @@ -141,11 +141,11 @@ deadline handling. ## Notes - `serve --stage-transport binary` is the tuned binary stage-to-stage path. -- Binary stages participate in the breaking generation-17 stage protocol. - Stage compatibility requires the complete `stage-generation-17` control, +- Binary stages participate in the breaking generation-18 stage protocol. + Stage compatibility requires the complete `stage-generation-18` 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-17 topology. + during split planning rather than being mixed into a generation-18 topology. - Binary stages accept upstream protocol connections concurrently. Model execution remains serialized by the per-process runtime lock, but readiness, abandoned, or broken connections do not monopolize the listener and block the diff --git a/crates/skippy-serving/src/binary_transport/binary_kv.rs b/crates/skippy-serving/src/binary_transport/binary_kv.rs index 6c8810e9..9d1693ce 100644 --- a/crates/skippy-serving/src/binary_transport/binary_kv.rs +++ b/crates/skippy-serving/src/binary_transport/binary_kv.rs @@ -343,6 +343,7 @@ pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( || message.kind.requires_predicted_reply() || !kv.should_lookup() || token_ids.is_empty() + || !runtime.restores_prefixes_alone() { return result; } @@ -1059,6 +1060,54 @@ mod tests { assert_eq!(record_plan[0].namespace, lookup_plan[0].namespace); assert_ne!(record_plan[0].page_id, lookup_plan[0].page_id); } + + // Stage 0 computes a prefill from the first position when no restore + // ran through the chain; a final stage that restored part of it from + // its own cache would hold a turn that starts later than stage 0's. + #[test] + fn a_stage_that_issues_receipts_does_not_restore_a_prefill_alone() { + use crate::telemetry::{Telemetry, TelemetryLevel}; + let mut config = prefix_cache_test_config(); + config.stage_index = 1; + config.downstream = None; + let kv = std::sync::Arc::new( + KvStageIntegration::from_test_state(&config, skippy_runtime::ModelStateKind::Dense) + .unwrap() + .expect("resident prefix cache enabled"), + ); + let telemetry = Telemetry::new(None, 1, config.clone(), TelemetryLevel::Off); + let mut message = prefill_message(); + let tokens = (0..512).collect::>(); + message.token_count = 512; + let lookup = |runtime: &mut crate::runtime_state::RuntimeState| { + let prepared = + super::prepare_binary_prefill(&config, Some(&kv), "session", &message, &tokens, 0); + super::maybe_lookup_binary_prefill( + &config, runtime, prepared, &telemetry, "session", &message, &tokens, + ) + .stats + }; + + let mut runtime = crate::runtime_state::RuntimeState::new_modelless_for_test(1); + assert_eq!( + lookup(&mut runtime).kv_lookup_misses, + 1, + "without receipts the stage looks its cache up" + ); + runtime.set_receipts(std::sync::Arc::new( + crate::receipts::StageReceipts::for_test(1), + )); + let stats = lookup(&mut runtime); + assert_eq!( + ( + stats.kv_lookup_hits, + stats.kv_lookup_misses, + stats.kv_lookup_errors + ), + (0, 0, 0), + "a stage that issues receipts computes what stage 0 computes" + ); + } } #[cfg(test)] diff --git a/crates/skippy-serving/src/binary_transport/binary_messaging.rs b/crates/skippy-serving/src/binary_transport/binary_messaging.rs index a9077470..0b5bd073 100644 --- a/crates/skippy-serving/src/binary_transport/binary_messaging.rs +++ b/crates/skippy-serving/src/binary_transport/binary_messaging.rs @@ -448,6 +448,7 @@ fn run_binary_stage( l3_manager, compute_meter, split_dflash, + receipts, } = options; // With an OpenAI frontend, a stop request closes HTTP admission first. // Keep worker connections and prediction returns alive until Axum drains. @@ -527,6 +528,9 @@ fn run_binary_stage( // (#1954). let max_inflight = max_inflight .min(usize::try_from(lock_runtime(&runtime).lane_count()).unwrap_or(usize::MAX)); + if let Some(receipts) = receipts { + crate::receipts::start(receipts, &config, runtime.clone())?; + } let (input_boundary, output_boundary) = { let runtime = lock_runtime(&runtime); ( @@ -709,6 +713,7 @@ fn run_binary_stage( let worker_shutdown = shutdown.clone(); let prediction_returns = prediction_returns.clone(); let prediction_return_sinks = prediction_return_sinks.clone(); + let receipts_runtime = runtime.clone(); let session_ownership = session_ownership.clone(); let worker_control = Arc::new(ConnectionWorkerControl::default()); worker_control @@ -747,6 +752,13 @@ fn run_binary_stage( } return prediction_return_sinks.insert_opened_sink(first_message, upstream); } + if first_message.kind == WireMessageKind::Receipts { + return crate::receipts::serve_stage_connection( + &receipts_runtime, + upstream, + first_message, + ); + } // Dedicated connect-failure event at the fallible // boundary (see acquire_downstream_or_emit_connect_error): // the first message's request/session ids are real, the diff --git a/crates/skippy-serving/src/binary_transport/direct_return.rs b/crates/skippy-serving/src/binary_transport/direct_return.rs index 20e44722..36e7af1e 100644 --- a/crates/skippy-serving/src/binary_transport/direct_return.rs +++ b/crates/skippy-serving/src/binary_transport/direct_return.rs @@ -283,14 +283,30 @@ impl PredictionReturnHub { Ok(PredictionReturnReceiver { key, hub: self.clone(), - receiver, + receiver: Mutex::new(receiver), }) } + /// Gives the waiter of `key` a new channel and closes the streams read + /// for it so far. Their readers keep the old channel, so what they + /// report next, such as the end of their stream, reaches nobody. + fn restart_waiter(&self, key: PredictionReturnKey) -> ReturnChannel { + let (sender, receiver) = mpsc::channel(); + if let Ok(mut waiters) = self.waiters.lock() { + waiters.insert(key, sender); + } + self.close_streams(key); + receiver + } + pub(crate) fn unregister(&self, key: PredictionReturnKey) { if let Ok(mut waiters) = self.waiters.lock() { waiters.remove(&key); } + self.close_streams(key); + } + + fn close_streams(&self, key: PredictionReturnKey) { let streams = self .streams .lock() @@ -464,9 +480,13 @@ impl Drop for TrackedStream<'_> { pub(crate) struct PredictionReturnReceiver { key: PredictionReturnKey, hub: Arc, - receiver: mpsc::Receiver>, + /// Replaced by [`Self::restart`], which the request's own thread calls + /// between its waits. + receiver: Mutex, } +type ReturnChannel = mpsc::Receiver>; + impl PredictionReturnReceiver { pub(crate) fn attach_opened_stream(&self, stream: TcpStream) { let hub = self.hub.clone(); @@ -478,18 +498,43 @@ impl PredictionReturnReceiver { }); } + /// Starts the request's replies over, after a stop ended an attempt that + /// used the same request ids, such as a missed prefix restore. The stop + /// closes the attempt's return streams, and the end of each stream is + /// reported to the channel its reader took. Those ends belong to the + /// attempt: the next attempt's replies arrive on a new channel, so the + /// end of a stream the stop closed cannot fail them. + pub(crate) fn restart(&self) { + let receiver = self.hub.restart_waiter(self.key); + *self + .receiver + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = receiver; + } + + fn recv_timeout(&self, timeout: Duration) -> Result> { + let received = self + .receiver + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .recv_timeout(timeout); + match received { + Ok(Ok(reply)) => Ok(Some(reply)), + Ok(Err(error)) => Err(anyhow!(error)), + Err(RecvTimeoutError::Timeout) => Ok(None), + Err(RecvTimeoutError::Disconnected) => { + Err(anyhow!("prediction return channel disconnected")) + } + } + } + pub(crate) fn recv_expected_timeout( &self, expected: WireReplyKind, timeout: Duration, ) -> Result> { - let reply = match self.receiver.recv_timeout(timeout) { - Ok(Ok(reply)) => reply, - Ok(Err(error)) => return Err(anyhow!(error)), - Err(RecvTimeoutError::Timeout) => return Ok(None), - Err(RecvTimeoutError::Disconnected) => { - return Err(anyhow!("prediction return channel disconnected")); - } + let Some(reply) = self.recv_timeout(timeout)? else { + return Ok(None); }; validate_expected_reply(reply, std::slice::from_ref(&expected)).map(Some) } @@ -501,13 +546,8 @@ impl PredictionReturnReceiver { expected: &[WireReplyKind], timeout: Duration, ) -> Result> { - let reply = match self.receiver.recv_timeout(timeout) { - Ok(Ok(reply)) => reply, - Ok(Err(error)) => return Err(anyhow!(error)), - Err(RecvTimeoutError::Timeout) => return Ok(None), - Err(RecvTimeoutError::Disconnected) => { - return Err(anyhow!("prediction return channel disconnected")); - } + let Some(reply) = self.recv_timeout(timeout)? else { + return Ok(None); }; validate_expected_reply(reply, expected).map(Some) } @@ -744,7 +784,8 @@ fn prediction_return_open_message(request_id: u64, session_id: u64) -> StageWire mod tests { use super::*; use skippy_protocol::binary::{ - recv_ready, recv_reply, send_reply_predicted_with_stats, state_flags, + recv_ready, recv_reply, send_reply_ack_with_stats, send_reply_predicted_with_stats, + state_flags, }; use std::io::Write; @@ -960,6 +1001,58 @@ mod tests { handle.join().unwrap().unwrap(); } + /// Opens a return stream for `request_id`/`session_id` on `hub`, as the + /// final stage does, and returns its peer end and reader. + fn open_return_stream( + hub: &Arc, + request_id: u64, + session_id: u64, + ) -> (TcpStream, JoinHandle>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + let open = prediction_return_open_message(request_id, session_id); + let hub = hub.clone(); + let reader = thread::spawn(move || hub.handle_return_connection(open, server)); + (client, reader) + } + + // A missed prefix restore ends with a stop that closes the final stage's + // return stream; the request then prefills in full under the same ids. + #[test] + fn a_return_stream_closed_by_a_restore_cleanup_does_not_fail_the_retry() { + let (request_id, session_id) = (71, 73); + let hub = Arc::new(PredictionReturnHub::default()); + let receiver = hub.register(request_id, session_id).unwrap(); + + // the restore attempt: the final stage misses and says so + let (mut attempt, attempt_reader) = open_return_stream(&hub, request_id, session_id); + send_reply_ack_with_stats(&mut attempt, Default::default()).unwrap(); + let miss = receiver + .recv_one_of_timeout( + &[WireReplyKind::PredictedToken, WireReplyKind::Ack], + Duration::from_secs(5), + ) + .unwrap() + .expect("the miss reply"); + assert_eq!(miss.kind, WireReplyKind::Ack); + // the cleanup stop closes the stream before it is acknowledged + drop(attempt); + attempt_reader.join().unwrap().unwrap(); + receiver.restart(); + + // the full prefill: the final stage opens a new stream + let (mut retry, retry_reader) = open_return_stream(&hub, request_id, session_id); + send_reply_predicted_with_stats(&mut retry, 42, Default::default()).unwrap(); + let reply = receiver + .recv_expected_timeout(WireReplyKind::PredictedToken, Duration::from_secs(5)) + .expect("the retry's reply, not the end of the restore's stream") + .expect("a reply within the timeout"); + assert_eq!(reply.predicted, 42); + drop(retry); + retry_reader.join().unwrap().unwrap(); + } + /// Direct-return transport preserves typed native MTP draft evidence. #[test] fn direct_prediction_return_preserves_typed_native_mtp_draft() { diff --git a/crates/skippy-serving/src/binary_transport/options.rs b/crates/skippy-serving/src/binary_transport/options.rs index c05deaf8..6c4e8dbb 100644 --- a/crates/skippy-serving/src/binary_transport/options.rs +++ b/crates/skippy-serving/src/binary_transport/options.rs @@ -42,6 +42,8 @@ pub struct BinaryStageOptions { pub l3_manager: Option, /// This stage's part in a split DFlash plan. pub split_dflash: Option, + /// Opt-in verifiable inference receipts. `None` leaves them off. + pub receipts: Option, } #[derive(Clone)] @@ -132,6 +134,7 @@ mod tests { reply_credit_limit: None, async_prefill_forward: false, downstream_wire_condition: WireCondition::new(0.0, None).unwrap(), + receipts: None, downstream_connect_timeout_secs: 1, native_mtp_enabled: false, last_stage_decode_batch: None, diff --git a/crates/skippy-serving/src/binary_transport/peer_sampling.rs b/crates/skippy-serving/src/binary_transport/peer_sampling.rs index fe19a0e1..3305ee2b 100644 --- a/crates/skippy-serving/src/binary_transport/peer_sampling.rs +++ b/crates/skippy-serving/src/binary_transport/peer_sampling.rs @@ -49,6 +49,7 @@ pub(in crate::binary_transport) fn runtime_sampling_config( reasoning_budget: skippy_runtime::ReasoningBudget::Resolved( sampling.reasoning_budget_tokens, ), + indexed_draw: (sampling.flags & sampling_flags::INDEXED_DRAW) != 0, ..SamplingConfig::default() }; config.logit_bias = sampling diff --git a/crates/skippy-serving/src/binary_transport/stage_execution.rs b/crates/skippy-serving/src/binary_transport/stage_execution.rs index 9e887c80..8f48307c 100644 --- a/crates/skippy-serving/src/binary_transport/stage_execution.rs +++ b/crates/skippy-serving/src/binary_transport/stage_execution.rs @@ -358,6 +358,8 @@ pub(in crate::binary_transport) fn estimated_reply_wire_bytes( WireReplyKind::PredictedToken => 1, WireReplyKind::PredictedTokens => predicted_token_count, WireReplyKind::TokenScores => predicted_token_count + 1, + // a receipts reply is not a stage reply; it has its own frame + WireReplyKind::Receipts => 0, }; REPLY_HEADER_BYTES + token_count * std::mem::size_of::() + STAGE_REPLY_STATS_WIRE_BYTES } @@ -885,7 +887,8 @@ fn execute_binary_stage_message( | WireMessageKind::RestorePrefill | WireMessageKind::TryRestorePrefill | WireMessageKind::TryRestorePrefillDecode - | WireMessageKind::PredictionReturnOpen => { + | WireMessageKind::PredictionReturnOpen + | WireMessageKind::Receipts => { bail!("message kind is not executable") } } diff --git a/crates/skippy-serving/src/embedded.rs b/crates/skippy-serving/src/embedded.rs index 7cae0f1f..264d7f49 100644 --- a/crates/skippy-serving/src/embedded.rs +++ b/crates/skippy-serving/src/embedded.rs @@ -102,6 +102,8 @@ pub struct EmbeddedRuntimeOptions { /// Optional session-lifecycle observer, attached to the loaded /// `RuntimeState` at construction (plan task 12, §8.7). pub session_lifecycle_observer: Option>, + /// Issue inference receipts for the turns this runtime serves. + pub receipts: Option, } pub struct SkippyRuntimeHandle { @@ -225,6 +227,9 @@ impl SkippyRuntimeHandle { options.session_lifecycle_observer.clone(), )? .with_context(|| format!("stage {} requires model_path", options.config.stage_id))?; + if let Some(receipts) = options.receipts { + crate::receipts::start(receipts, &options.config, runtime.clone())?; + } telemetry.emit( "stage.embedded_runtime_ready", lifecycle_attrs(&options.config), @@ -277,6 +282,9 @@ impl SkippyRuntimeHandle { options.session_lifecycle_observer.clone(), )? .with_context(|| format!("stage {} requires model_path", options.config.stage_id))?; + if let Some(receipts) = options.receipts { + crate::receipts::start(receipts, &options.config, runtime.clone())?; + } telemetry.emit( "stage.embedded_runtime_ready", lifecycle_attrs(&options.config), @@ -305,6 +313,25 @@ impl SkippyRuntimeHandle { self.runtime.clone() } + /// The receipts route for the OpenAI surface, when this runtime issues + /// receipts ([`crate::receipts::client_router`]). + pub fn receipts_router(&self) -> Option { + crate::receipts::client_router(&self.runtime) + } + + /// The backend this runtime's receipts name, when it issues receipts + /// ([`crate::receipts::backend_name`]). + pub fn receipts_backend(&self) -> Option { + crate::receipts::backend_name(&self.runtime) + } + + /// Whether this runtime issues receipts on a stage with recurrent + /// state, which gives a turn that continues a cached prefix none + /// ([`crate::receipts::keeps_recurrent_state`]). + pub fn receipts_keep_recurrent_state(&self) -> bool { + crate::receipts::keeps_recurrent_state(&self.runtime) + } + pub fn telemetry(&self) -> Telemetry { self.telemetry.clone() } @@ -569,9 +596,28 @@ pub fn start_openai_backend_with_tokenizer_and_lifecycle_observer( backend: Arc, tokenizer: TokenizerCapability, lifecycle_observer: Option>, +) -> EmbeddedServerHandle { + start_openai_backend_with_routes( + bind_addr, + backend, + tokenizer, + lifecycle_observer, + Router::new(), + ) +} + +/// [`start_openai_backend_with_tokenizer_and_lifecycle_observer`] with +/// `routes` merged in, such as [`SkippyRuntimeHandle::receipts_router`]. +pub fn start_openai_backend_with_routes( + bind_addr: SocketAddr, + backend: Arc, + tokenizer: TokenizerCapability, + lifecycle_observer: Option>, + routes: Router, ) -> EmbeddedServerHandle { let router = openai_backend_router_with_lifecycle_observer(backend, lifecycle_observer) - .merge(tokenizer_http_router(tokenizer)); + .merge(tokenizer_http_router(tokenizer)) + .merge(routes); spawn_openai_backend(bind_addr, router) } diff --git a/crates/skippy-serving/src/frontend.rs b/crates/skippy-serving/src/frontend.rs index 5b07ca06..f0c65b20 100644 --- a/crates/skippy-serving/src/frontend.rs +++ b/crates/skippy-serving/src/frontend.rs @@ -10,6 +10,7 @@ mod generation_commit_batcher; mod generation_flow; mod generation_receipt; mod guardrails; +mod inference_receipts; pub(crate) mod iteration_scheduler; mod linear_proposal; mod local_generation; diff --git a/crates/skippy-serving/src/frontend/backend.rs b/crates/skippy-serving/src/frontend/backend.rs index 04fe4c54..f12aa66f 100644 --- a/crates/skippy-serving/src/frontend/backend.rs +++ b/crates/skippy-serving/src/frontend/backend.rs @@ -1288,7 +1288,10 @@ impl StageOpenAiBackend { { return; } - let _ = sender.send_terminal(Ok(GenerationStreamEvent::Done(finish_reason))); + let _ = sender.send_terminal(Ok(GenerationStreamEvent::Done( + finish_reason, + output.receipt.take(), + ))); } Err(error) => { backend.observe_generation_failed(); diff --git a/crates/skippy-serving/src/frontend/backend/inference.rs b/crates/skippy-serving/src/frontend/backend/inference.rs index 7fbf61ce..7b2fa909 100644 --- a/crates/skippy-serving/src/frontend/backend/inference.rs +++ b/crates/skippy-serving/src/frontend/backend/inference.rs @@ -54,10 +54,15 @@ impl InferenceBackend for StageOpenAiBackend { self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = resolve_chat_request_defaults(&request, &self.request_defaults.snapshot())?; + let body_seed = request.seed; apply_chat_request_defaults(&mut request, &request_defaults)?; ensure_chat_runtime_features_supported(&request)?; - let sampling = chat_sampling_config(&request, &request_defaults)? - .with_penalty_windows_within(self.ctx_size); + let sampling = crate::receipts::prefer_receipt_seed( + chat_sampling_config(&request, &request_defaults)? + .with_penalty_windows_within(self.ctx_size), + body_seed, + ids.receipt.as_ref().and_then(|receipt| receipt.seed), + ); let template_options = chat_template_options(&request, &request_defaults)?; let parse_chat_output = chat_output_parser_required(&request, &template_options); let template_timer = PhaseTimer::start(); @@ -210,10 +215,15 @@ impl InferenceBackend for StageOpenAiBackend { self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = resolve_chat_request_defaults(&request, &self.request_defaults.snapshot())?; + let body_seed = request.seed; apply_chat_request_defaults(&mut request, &request_defaults)?; ensure_chat_runtime_features_supported(&request)?; - let sampling = chat_sampling_config(&request, &request_defaults)? - .with_penalty_windows_within(self.ctx_size); + let sampling = crate::receipts::prefer_receipt_seed( + chat_sampling_config(&request, &request_defaults)? + .with_penalty_windows_within(self.ctx_size), + body_seed, + ids.receipt.as_ref().and_then(|receipt| receipt.seed), + ); let include_usage = request.include_usage(); let template_options = chat_template_options(&request, &request_defaults)?; let parse_chat_output = chat_output_parser_required(&request, &template_options); @@ -311,10 +321,14 @@ impl InferenceBackend for StageOpenAiBackend { self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = resolve_completion_request_defaults(&request, &self.request_defaults.snapshot()); + let body_seed = request.seed; apply_completion_request_defaults(&mut request, &request_defaults); ensure_completion_runtime_features_supported(&request)?; - let sampling = - completion_sampling_config(&request)?.with_penalty_windows_within(self.ctx_size); + let sampling = crate::receipts::prefer_receipt_seed( + completion_sampling_config(&request)?.with_penalty_windows_within(self.ctx_size), + body_seed, + ids.receipt.as_ref().and_then(|receipt| receipt.seed), + ); let max_tokens = GenerationTokenLimit::from_request(request.max_tokens, self.default_max_tokens); let prompt_timer = PhaseTimer::start(); @@ -412,10 +426,14 @@ impl InferenceBackend for StageOpenAiBackend { self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = resolve_completion_request_defaults(&request, &self.request_defaults.snapshot()); + let body_seed = request.seed; apply_completion_request_defaults(&mut request, &request_defaults); ensure_completion_runtime_features_supported(&request)?; - let sampling = - completion_sampling_config(&request)?.with_penalty_windows_within(self.ctx_size); + let sampling = crate::receipts::prefer_receipt_seed( + completion_sampling_config(&request)?.with_penalty_windows_within(self.ctx_size), + body_seed, + ids.receipt.as_ref().and_then(|receipt| receipt.seed), + ); let include_usage = request.include_usage(); let max_tokens = GenerationTokenLimit::from_request(request.max_tokens, self.default_max_tokens); diff --git a/crates/skippy-serving/src/frontend/backend/tests.rs b/crates/skippy-serving/src/frontend/backend/tests.rs index 1504fa19..babbb039 100644 --- a/crates/skippy-serving/src/frontend/backend/tests.rs +++ b/crates/skippy-serving/src/frontend/backend/tests.rs @@ -195,7 +195,7 @@ fn terminal_frames_are_delivered_after_the_request_is_cancelled() { ); sender - .send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop))) + .send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop, None))) .expect("terminal frames must still reach a live, cancelled-but-draining receiver"); let received = rx @@ -203,7 +203,7 @@ fn terminal_frames_are_delivered_after_the_request_is_cancelled() { .expect("the terminal frame must be enqueued, not silently swallowed"); assert!(matches!( received, - Ok(GenerationStreamEvent::Done(FinishReason::Stop)) + Ok(GenerationStreamEvent::Done(FinishReason::Stop, None)) )); let send_result = sender.send( @@ -286,7 +286,7 @@ fn terminal_frames_are_dropped_once_the_receiver_is_proven_unreachable() { ); let started = Instant::now(); - let terminal = sender.send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop))); + let terminal = sender.send_terminal(Ok(GenerationStreamEvent::Done(FinishReason::Stop, None))); let elapsed = started.elapsed(); assert!( diff --git a/crates/skippy-serving/src/frontend/embedded_generation.rs b/crates/skippy-serving/src/frontend/embedded_generation.rs index 285453bc..8822641e 100644 --- a/crates/skippy-serving/src/frontend/embedded_generation.rs +++ b/crates/skippy-serving/src/frontend/embedded_generation.rs @@ -19,6 +19,7 @@ use crate::binary_transport::{ forwarded_stage_message_timed, run_binary_stage_message, write_stage_message_conditioned, }; use crate::frontend::embedded_execution::{StaleWindowDiscard, VerifyRetirement}; +use crate::frontend::inference_receipts::SampledTokens; use crate::frontend::request::wire_sampling_config; use crate::frontend::speculative::{ InferenceSpeculativeStats, classify_verify_window_with_threshold, @@ -77,6 +78,8 @@ impl StageOpenAiBackend { if request.config.downstream.is_none() { return self.generate_embedded_request_locally(request, on_token); } + let inference_receipt_tokens = SampledTokens::default(); + let on_token = inference_receipt_tokens.observing(on_token); let wire_sampling = wire_sampling_config(request.sampling); let session_id = request.ids.session_id; @@ -2296,6 +2299,10 @@ impl StageOpenAiBackend { })(); finish_generation_lifecycle(lifecycle, lifecycle_cancelled, result.is_ok()); + if result.is_ok() { + cache_stats.receipt = + self.finish_split_receipt_turn(&request, &session_key, &inference_receipt_tokens); + } self.finish_embedded_generation_session(&request, lane_pool, lane, &result, &session_key)?; result?; Ok(cache_stats) diff --git a/crates/skippy-serving/src/frontend/generation/cache_hints.rs b/crates/skippy-serving/src/frontend/generation/cache_hints.rs index d8d37e4f..fa47f6f9 100644 --- a/crates/skippy-serving/src/frontend/generation/cache_hints.rs +++ b/crates/skippy-serving/src/frontend/generation/cache_hints.rs @@ -52,9 +52,19 @@ pub(in crate::frontend) struct InferenceGenerationIds { /// runtime-event adapter can correlate a generation under the same /// request root Task 11's OpenAI observer reserves. pub(in crate::frontend) frontend_request_id: Option<[u8; 16]>, + /// The inference-receipt binding the request asked for. + pub(in crate::frontend) receipt: Option, } impl InferenceGenerationIds { + pub(in crate::frontend) fn with_receipt( + mut self, + receipt: Option, + ) -> Self { + self.receipt = receipt; + self + } + pub(in crate::frontend) fn new_with_trust( cache: InferenceCacheHints, agent_session_id: Option<&str>, @@ -88,6 +98,7 @@ impl InferenceGenerationIds { agent_session_trusted: agent_session_trusted && agent_session_id.is_some(), cache, frontend_request_id, + receipt: None, } } @@ -358,6 +369,8 @@ pub(in crate::frontend) struct GenerationCacheStats { pub(in crate::frontend) activation_wire: Option, /// The prompt prefix a split restored on every stage, on its stage 0. pub(in crate::frontend) split_prefix_cache: Option, + /// The turn's receipt, when the request asked for a bound one. + pub(in crate::frontend) receipt: Option, } impl Default for GenerationCacheStats { @@ -379,6 +392,7 @@ impl Default for GenerationCacheStats { token_logprobs: None, activation_wire: None, split_prefix_cache: None, + receipt: None, } } } diff --git a/crates/skippy-serving/src/frontend/generation/execution.rs b/crates/skippy-serving/src/frontend/generation/execution.rs index bd08c33c..d6d5e7df 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_receipt(context.receipt()) } /// 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..9a3bcad3 100644 --- a/crates/skippy-serving/src/frontend/generation/parsing.rs +++ b/crates/skippy-serving/src/frontend/generation/parsing.rs @@ -241,7 +241,8 @@ pub(in crate::frontend) fn generation_response_from_generated_text( }], output.usage(), output.timings(), - ); + ) + .with_receipt(output.receipt.clone()); } let mut response = GenerationResponse::new_with_reason( @@ -250,7 +251,8 @@ pub(in crate::frontend) fn generation_response_from_generated_text( output.usage(), output.finish_reason, ) - .with_timings(output.timings()); + .with_timings(output.timings()) + .with_receipt(output.receipt.clone()); if let Some(choice) = response.choices.first_mut() { choice.logprobs = chat_logprobs(output); } @@ -289,7 +291,8 @@ pub(in crate::frontend) fn completion_response_from_generated_text( output.usage(), output.finish_reason, ) - .with_timings(output.timings()); + .with_timings(output.timings()) + .with_receipt(output.receipt.clone()); if let Some(choice) = response.choices.first_mut() { choice.logprobs = completion_logprobs(output); } diff --git a/crates/skippy-serving/src/frontend/generation/streaming.rs b/crates/skippy-serving/src/frontend/generation/streaming.rs index bcd2df8a..aaa7538f 100644 --- a/crates/skippy-serving/src/frontend/generation/streaming.rs +++ b/crates/skippy-serving/src/frontend/generation/streaming.rs @@ -40,7 +40,8 @@ pub(in crate::frontend) enum GenerationStreamEvent { ReasoningDelta(String), ToolCalls(Value), Usage(Usage, Option>), - Done(FinishReason), + /// The last event, with the turn's receipt when the request asked for one. + Done(FinishReason, Option), } /// Tracks what has already been sent for one streaming chat completion, and @@ -266,6 +267,7 @@ pub(in crate::frontend) fn generation_event_to_inference_event( }], usage: None, timings: None, + receipt: None, }), GenerationStreamEvent::ToolCalls(tool_calls) => Ok(GenerationEvent { id: skippy_inference_api::completion_id("chatcmpl"), @@ -284,14 +286,15 @@ pub(in crate::frontend) fn generation_event_to_inference_event( }], usage: None, timings: None, + receipt: None, }), GenerationStreamEvent::Usage(usage, timings) => Ok(GenerationEvent::usage_with_timings( model.to_string(), usage, timings, )), - GenerationStreamEvent::Done(reason) => { - Ok(GenerationEvent::done_with_reason(model.to_string(), reason)) + GenerationStreamEvent::Done(reason, receipt) => { + Ok(GenerationEvent::done_with_reason(model.to_string(), reason).with_receipt(receipt)) } } } @@ -311,8 +314,8 @@ pub(in crate::frontend) fn generation_event_to_completion_chunk( usage, timings, )), - GenerationStreamEvent::Done(reason) => { - Ok(CompletionChunk::done_with_reason(model.to_string(), reason)) + GenerationStreamEvent::Done(reason, receipt) => { + Ok(CompletionChunk::done_with_reason(model.to_string(), reason).with_receipt(receipt)) } } } @@ -557,6 +560,7 @@ where token_logprobs, activation_wire: cache_stats.activation_wire, generation_stats: None, + receipt: cache_stats.receipt, }) } diff --git a/crates/skippy-serving/src/frontend/generation/types.rs b/crates/skippy-serving/src/frontend/generation/types.rs index bb35b31c..f0a1c8dd 100644 --- a/crates/skippy-serving/src/frontend/generation/types.rs +++ b/crates/skippy-serving/src/frontend/generation/types.rs @@ -457,6 +457,8 @@ pub(in crate::frontend) struct GeneratedText { pub(in crate::frontend) eog_check_ms: f64, /// One entry per completion token, when the request asked for logprobs. pub(in crate::frontend) token_logprobs: Option>, + /// The turn's receipt, when the request asked for a bound one. + pub(in crate::frontend) receipt: Option, pub(in crate::frontend) activation_wire: Option, /// Filled in once the generation finishes, and handed to the stats /// observer after admission has been timed. `None` when no observer is diff --git a/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs b/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs index f3fe8981..26b28a7d 100644 --- a/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs +++ b/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs @@ -126,6 +126,7 @@ impl StageOpenAiBackend { ))); } sampling.resolve_reasoning_budget(max_tokens); + self.prepare_receipt_draw(&mut sampling, &ids, prompt.chat_parse_metadata.as_deref()); // This is an optional cache candidate. The already-rendered prompt is // valid even when its second, assistant-marker-free rendering cannot // be tokenized, so bypass the candidate rather than failing the chat diff --git a/crates/skippy-serving/src/frontend/inference_receipts.rs b/crates/skippy-serving/src/frontend/inference_receipts.rs new file mode 100644 index 00000000..19aa294d --- /dev/null +++ b/crates/skippy-serving/src/frontend/inference_receipts.rs @@ -0,0 +1,168 @@ +//! Inference receipts for the turns stage 0 serves ([`crate::receipts`]): +//! what the generation paths call to commit a turn's receipt, and what a +//! stage that issues receipts does differently while it generates. Not the +//! generation receipts of `generation_receipt`, which record what the +//! frontend emitted. +//! +//! The receipt is committed after the turn and before its session is +//! cleaned up, while the session still holds its native sequence. A turn +//! this stage serves alone whose receipt is committed here therefore does +//! not run on the scheduler's built-in driver, which resets the session and +//! hands its lane to the next request as the sequence ends; it runs on the +//! feature loop, whose session lives until the request cleans it up. Were a +//! commit to come late all the same, it names its turn, and the recorder +//! gives it that turn's leaves or none +//! ([`skippy_receipts::recorder::TurnId`]). +//! +//! Of the turns this stage serves alone, only one that asks for a bound +//! receipt is committed: a single stage serves openings only on its OpenAI +//! address, which opens bound receipts alone, so an unbound one would be of +//! no use. Other such turns take no runtime lock here. A turn of a split is +//! committed either way. + +use std::cell::Cell; + +use crate::frontend::generation::{ + EmbeddedStageZeroGeneration, InferenceBackendMode, InferenceGenerationIds, LocalGeneration, + StageOpenAiBackend, +}; +use crate::receipts::TurnTokens; +use crate::runtime_state::panic_recovery::lock_runtime; + +/// The tokens a turn sampled, as its receipt needs them: a receipt names +/// the last sampled token, which no ubatch computes, and ends at the last +/// token fed. +#[derive(Default)] +pub(super) struct SampledTokens { + /// The last sampled token. + last: Cell>, + /// How many tokens the turn sampled, the last one included. + count: Cell, +} + +impl SampledTokens { + /// The turn sampled `token`. + pub(super) fn note(&self, token: i32) { + self.last.set(Some(token)); + self.count.set(self.count.get().saturating_add(1)); + } + + /// `on_token`, noting every token it is given first. + pub(super) fn observing<'a, R>( + &'a self, + mut on_token: impl FnMut(i32) -> R + 'a, + ) -> impl FnMut(i32) -> R + 'a { + move |token| { + self.note(token); + on_token(token) + } + } + + /// What stage 0 knows about the tokens of a turn whose prompt had + /// `prompt_tokens` tokens. + fn of_turn( + &self, + prompt_tokens: usize, + sampling: &skippy_runtime::SamplingConfig, + chat_sampling_metadata: Option<&str>, + ) -> TurnTokens { + TurnTokens { + generation_start: u32::try_from(prompt_tokens).unwrap_or(u32::MAX), + final_token: self.last.get(), + sampled: self.count.get(), + sampler: crate::receipts::sampler_statement(sampling, chat_sampling_metadata), + } + } +} + +impl StageOpenAiBackend { + /// Whether [`Self::finish_local_receipt_turn`] commits a receipt for + /// the request: it asked for a bound one, and the stage issues + /// receipts. + pub(super) fn commits_local_receipt(&self, request: &LocalGeneration<'_>) -> bool { + request.ids.receipt.is_some() && lock_runtime(&self.runtime).receipts().is_some() + } + + /// Commits and returns the receipt of a turn this stage served alone, + /// when the stage issues receipts and the request asked for a bound one. + /// `sampled` holds the tokens the turn sampled. Call it before the + /// turn's session is cleaned up. + pub(super) fn finish_local_receipt_turn( + &self, + request: &LocalGeneration<'_>, + session: &str, + sampled: &SampledTokens, + ) -> Option { + let bound = request.ids.receipt?; + crate::receipts::finish_stage_zero_turn( + &self.runtime, + request.ids.frontend_request_id, + Some(bound), + request.ids.request_id, + session, + sampled.of_turn( + request.prompt_token_ids.len(), + request.sampling, + request.chat_sampling_metadata, + ), + ) + } + + /// Commits the receipt of a turn of a split on every stage, when the + /// stage issues receipts, and returns it when the request asked for a + /// bound one. `sampled` holds the tokens the turn sampled. Call it + /// before the turn's session is cleaned up. + pub(super) fn finish_split_receipt_turn( + &self, + request: &EmbeddedStageZeroGeneration<'_>, + session: &str, + sampled: &SampledTokens, + ) -> Option { + crate::receipts::finish_stage_zero_turn( + &self.runtime, + request.ids.frontend_request_id, + request.ids.receipt, + request.ids.request_id, + session, + sampled.of_turn( + request.prompt_token_ids.len(), + request.sampling, + request.chat_sampling_metadata, + ), + ) + } + + /// Gives a sampled turn that will get a receipt a draw its client can + /// replay ([`crate::receipts::make_draw_replayable`]). A turn this stage + /// serves alone gets a receipt when the request asks for a bound one, + /// and a turn of a split either way. A greedy turn takes no runtime lock + /// here. + pub(super) fn prepare_receipt_draw( + &self, + sampling: &mut skippy_runtime::SamplingConfig, + ids: &InferenceGenerationIds, + chat_sampling_metadata: Option<&str>, + ) { + let asked = match self.mode { + InferenceBackendMode::LocalRuntime => ids.receipt.is_some(), + InferenceBackendMode::EmbeddedStageZero { .. } => true, + }; + if !asked || !crate::receipts::draws_from_the_chain(sampling, chat_sampling_metadata) { + return; + } + if lock_runtime(&self.runtime).receipts().is_none() { + return; + } + let client_seed = ids.receipt.and_then(|receipt| receipt.seed); + crate::receipts::make_draw_replayable(sampling, chat_sampling_metadata, client_seed); + } + + /// A stage that issues receipts does not reuse tokens an earlier turn + /// generated. Those tokens would sit in the turn's cached prefix, and an + /// audit checks no sampled token there: a prefix holds only tokens a + /// request fed, and a turn whose prefix is longer than its prompt gets + /// no receipt (`StageReceipts::commit_turn`). + pub(super) fn receipts_forbid_generated_token_reuse(&self) -> bool { + lock_runtime(&self.runtime).receipts().is_some() + } +} 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..4e750506 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -13,6 +13,7 @@ use crate::frontend::generation::StageOpenAiBackend; use crate::frontend::generation::TokenControl; use crate::frontend::generation_receipt::GenerationLifecycleState; use crate::frontend::generation_receipt::complete_generation_before_cleanup; +use crate::frontend::inference_receipts::SampledTokens; use crate::frontend::iteration_scheduler::CacheRuntimeContext; use crate::frontend::iteration_scheduler::DirectIterationChannel; use crate::frontend::iteration_scheduler::ScheduledGenerationRequest; @@ -402,7 +403,9 @@ impl StageOpenAiBackend { receipt_request_id, receipt_session_id, ); + let inference_receipt_tokens = SampledTokens::default(); let mut emit_token = |token_id| { + inference_receipt_tokens.note(token_id); if let Some(observation) = receipt_observation.as_ref() && let Some(observation) = observation.borrow_mut().as_mut() { @@ -483,6 +486,10 @@ impl StageOpenAiBackend { Ok(()) }); let generation_succeeded = result.is_ok(); + if generation_succeeded { + cache_stats.receipt = + self.finish_local_receipt_turn(&request, &session_id, &inference_receipt_tokens); + } if receipt_cancelled { lifecycle.mark_cancelled(); } @@ -527,7 +534,10 @@ impl StageOpenAiBackend { ) // The built-in driver drops (and resets) the session as the sequence // ends, before the recorded logprobs can be taken. - && request.sampling.top_logprobs.is_none(); + && request.sampling.top_logprobs.is_none() + // Likewise before the turn's inference receipt can be committed: + // the freed lane would serve another request first. + && !self.commits_local_receipt(request); let mut attrs = self.openai_attrs(request.ids); attrs.insert("skippy.scheduler.eligible".to_string(), json!(eligible)); attrs.insert( diff --git a/crates/skippy-serving/src/frontend/prefix_cache.rs b/crates/skippy-serving/src/frontend/prefix_cache.rs index 7ab4b098..5315b7a0 100644 --- a/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -25,6 +25,7 @@ use crate::kv_integration::ExactStateKvExport; use crate::kv_integration::KvStageIntegration; use crate::kv_integration::proactive_eviction_attrs; use crate::kv_integration::proactive_eviction_error_kind; +use crate::runtime_state::panic_recovery::lock_runtime; use anyhow::Context; use serde_json::Value; use serde_json::json; @@ -313,7 +314,10 @@ impl StageOpenAiBackend { token_ids: &[i32], activation_width: i32, ) -> InferenceResult> { - if token_start != 0 { + // a later stage takes no prefix alone while the stage issues + // receipts (`maybe_lookup_binary_prefill`), so neither does stage 0: + // every stage must start a turn at the same position + if token_start != 0 || !lock_runtime(&self.runtime).restores_prefixes_alone() { return Ok(None); } let Some(kv) = self.kv.as_ref() else { @@ -797,6 +801,7 @@ impl StageOpenAiBackend { if request.prompt_token_ids.is_empty() || !kv.should_lookup() || !request_allows_exact_replay(request) + || self.receipts_forbid_generated_token_reuse() { return Ok(None); } @@ -902,7 +907,10 @@ impl StageOpenAiBackend { let Some(kv) = self.kv.as_ref() else { return Ok(None); }; - if request.prompt_token_ids.is_empty() || !kv.should_lookup() { + if request.prompt_token_ids.is_empty() + || !kv.should_lookup() + || self.receipts_forbid_generated_token_reuse() + { return Ok(None); } let timer = PhaseTimer::start(); @@ -1205,6 +1213,12 @@ impl StageOpenAiBackend { { let _ = recv_reply(&mut *downstream); } + // The stop closed the final stage's return stream for these ids; the + // request goes on under the same ids, and the end of that stream + // must not read as the end of the next attempt's. + if let Some(prediction_return) = request.prediction_return.as_ref() { + prediction_return.restart(); + } } } diff --git a/crates/skippy-serving/src/frontend/request.rs b/crates/skippy-serving/src/frontend/request.rs index d8e020d5..83f0c1c9 100644 --- a/crates/skippy-serving/src/frontend/request.rs +++ b/crates/skippy-serving/src/frontend/request.rs @@ -1657,6 +1657,7 @@ pub(super) fn sampling_config( samplers, reasoning_budget: ReasoningBudget::Unrestricted, top_logprobs: None, + indexed_draw: false, }) } @@ -1971,6 +1972,10 @@ pub(super) fn wire_sampling_config(sampling: &SamplingConfig) -> Option Result Result<()> { split_dflash: None, openai: None, l3_manager: None, + receipts: None, }); // Large filtered GGUF slices can take several minutes to materialize on // macOS even after the native library is warm. This test is opt-in and diff --git a/crates/skippy-serving/src/frontend/tests/prompting.rs b/crates/skippy-serving/src/frontend/tests/prompting.rs index 1d3cf8c6..dc0e7735 100644 --- a/crates/skippy-serving/src/frontend/tests/prompting.rs +++ b/crates/skippy-serving/src/frontend/tests/prompting.rs @@ -184,6 +184,7 @@ fn chat_response_from_parsed_message_separates_reasoning_content() { token_logprobs: None, activation_wire: None, generation_stats: None, + receipt: None, }; let parsed = ParsedChatMessage { content: Some("Final answer.".to_string()), @@ -243,6 +244,7 @@ fn generated_text_timings_are_present_without_native_mtp() { token_logprobs: None, activation_wire: None, generation_stats: None, + receipt: None, }; let timings = output.timings().expect("standard timings"); @@ -285,6 +287,7 @@ fn generated_text_timings_report_standalone_speculative_totals() { token_logprobs: None, activation_wire: None, generation_stats: None, + receipt: None, }; let timings = output.timings().expect("standalone speculative timings"); @@ -343,6 +346,7 @@ fn generated_text_timings_prefer_composite_proposal_totals() { token_logprobs: None, activation_wire: None, generation_stats: None, + receipt: None, }; let timings = output.timings().expect("timings"); @@ -379,6 +383,7 @@ fn split_prefix_cache_hit_is_reported_in_timings() { text_emit_ms: 0.0, eog_check_ms: 0.0, token_logprobs: None, + receipt: None, activation_wire: None, generation_stats: None, }; @@ -822,6 +827,7 @@ fn generated_text_with_logprobs() -> GeneratedText { ]), activation_wire: None, generation_stats: None, + receipt: None, } } @@ -975,3 +981,40 @@ async fn streaming_skip_chat_parsing_preserves_tool_shaped_text() -> Result<()> assert_eq!(reason, FinishReason::Stop); Ok(()) } + +#[test] +fn a_bound_receipt_rides_in_the_response_and_the_last_chunk() { + let mut output = generated_text_with_logprobs(); + let response = generation_response_from_generated_text("qwen".to_string(), &output, None); + assert_eq!(response.receipt, None); + output.receipt = Some(json!({"receipt_id": "r"})); + let response = generation_response_from_generated_text("qwen".to_string(), &output, None); + assert_eq!(response.receipt, output.receipt); + let response = completion_response_from_generated_text("qwen".to_string(), &output); + assert_eq!(response.receipt, output.receipt); + let parsed = ParsedChatMessage { + content: Some("Hi!".to_string()), + reasoning_content: None, + tool_calls: None, + }; + let response = + generation_response_from_generated_text("qwen".to_string(), &output, Some(parsed)); + assert_eq!(response.receipt, output.receipt); + + let done = generation_event_to_inference_event( + Ok(GenerationStreamEvent::Done( + FinishReason::Stop, + output.receipt.clone(), + )), + "qwen", + ) + .unwrap(); + assert_eq!(done.choices[0].finish_reason, Some(FinishReason::Stop)); + assert_eq!(done.receipt, output.receipt); + let delta = generation_event_to_inference_event( + Ok(GenerationStreamEvent::Delta("Hi".to_string())), + "qwen", + ) + .unwrap(); + assert_eq!(delta.receipt, None); +} diff --git a/crates/skippy-serving/src/lib.rs b/crates/skippy-serving/src/lib.rs index 4caaac2a..29718522 100644 --- a/crates/skippy-serving/src/lib.rs +++ b/crates/skippy-serving/src/lib.rs @@ -14,6 +14,7 @@ pub mod kv_integration; pub mod kv_proto; mod listener; pub mod readiness; +pub mod receipts; pub mod runtime_state; #[cfg(test)] @@ -50,7 +51,7 @@ pub use embedded::{ EmbeddedRuntimeOptions, EmbeddedRuntimeStatus, EmbeddedServerHandle, EmbeddedServerStatus, EmbeddedState, SkippyRuntimeHandle, start_binary_stage, start_embedded_openai, start_openai_backend, start_openai_backend_with_lifecycle_observer, - start_openai_backend_with_tokenizer, + start_openai_backend_with_routes, start_openai_backend_with_tokenizer, start_openai_backend_with_tokenizer_and_lifecycle_observer, }; pub use frontend::{ diff --git a/crates/skippy-serving/src/receipts.rs b/crates/skippy-serving/src/receipts.rs new file mode 100644 index 00000000..5f80259a --- /dev/null +++ b/crates/skippy-serving/src/receipts.rs @@ -0,0 +1,1023 @@ +//! Opt-in verifiable inference receipts for a serving stage. +//! +//! With receipts on, the stage's native receipt recorder feeds a +//! [`Recorder`] on a worker thread: leaf hashes per position, and a replay +//! log per turn of each sequence. +//! When stage 0 finishes a turn, it commits its own leaves, asks the next +//! stage to commit the same session and positions, and keeps the assembled +//! [`Receipt`] under the request's `x-request-id`. A challenge is opened by +//! replaying the turn in a scratch context of the stage model. Every stage +//! serves a small HTTP API on its receipts address ([`http_api`]): +//! +//! - `GET /receipts/{id}`: the receipt (stage 0); +//! - `POST /receipts/open`: open a [`Challenge`] on this stage and every +//! later one; each stage opens its picked layers, the input of layer 0 +//! if it holds layer 0, and the residuals at its boundaries; +//! - `POST /receipts/rows`: open the K and V rows of the attention blocks a +//! client picked after the opening ([`BlockChallenge`]) on this stage and +//! every later one; +//! - `POST /receipts/commit`: commit a session's positions (called by the +//! previous stage). +//! +//! A request that names a client VRF key (`x-receipt-client-key`) gets a +//! bound receipt: the key, the parent turn and the runtime go into the turn +//! root, which the stage signs with its node key. Every stage then opens +//! one challenge per bound receipt, and only with a VRF proof of the turn +//! root under that key, so the client cannot choose what it challenges +//! ([`admission`]). +//! +//! Openings carry activations derived from the prompt, so the API binds a +//! loopback address unless the operator allows a remote one. +//! +//! The stage owns its receipts: the runtime state holds them, and they go +//! with it when the model is unloaded, with their threads. The native +//! recorder, the HTTP routes and the stage connections only point at them. + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; + +use anyhow::{Context, Result, bail}; +use axum::Router; +use skippy_inference_api::ReceiptRequest; +use skippy_protocol::StageConfig; +use skippy_receipts::attention::opening::{BlockChallenge, RowsOpening}; +use skippy_receipts::commitment::hex_array; +use skippy_receipts::recorder::{KvStreams, Recorder, Replayer}; +use skippy_receipts::turn::{self, BindingRequest}; +use skippy_receipts::vrf; +use skippy_receipts::wire::{Challenge, Opening, RECEIPT_VERSION, Receipt, StageCommitment}; + +use crate::runtime_state::RuntimeState; +pub use crate::runtime_state::SessionTurn; +use crate::runtime_state::panic_recovery::lock_runtime; + +mod admission; +mod audited_backend; +mod audited_weights; +mod chain_server; +mod downstream; +mod http_api; +mod kept_turns; +mod kv_cache; +mod native; +mod opening_queue; +mod refusal; +mod reply_limits; +mod report_queue; +mod sampler_statement; +mod upkeep; + +use downstream::{CommitRequest, ForwardedOpen, ForwardedRows}; +use kept_turns::{KeptTurns, LaterStages, Outcome, Reservation}; +use reply_limits::ReplyLimits; +pub(crate) use sampler_statement::{ + draws_from_the_chain, make_draw_replayable, prefer_receipt_seed, sampler_statement, +}; + +/// Request header of `POST /receipts/open` between stages: the hex turn +/// root of a bound receipt, which the challenge's proof is over. +pub const TURN_ROOT_HEADER: &str = "x-receipt-turn-root"; +/// Request header of `POST /receipts/rows` between stages: the hex digest +/// of the opening stage 0 signed, which the rows' proof is over. +pub const OPENING_DIGEST_HEADER: &str = "x-receipt-opening-digest"; + +/// Checks that a turn computed the end of its prompt. A stage that issues +/// receipts does not reuse generated tokens, so a cached prefix holds only +/// tokens a request fed: the audit checks no sampled token below the turn. +/// And the prefix lookup leaves out the last prompt token (`prompt[..len - +/// 1]` in `backend.rs` and `token_generation.rs`), so the turn samples its +/// first token from a position it computed. A client refuses a receipt that +/// does not (`skippy_receipts::binding::verify_shape`). +fn check_turn_start(generation_start: u32, positions: &std::ops::Range) -> Result<()> { + if generation_start < positions.start { + bail!( + "the turn's cached prefix of {} positions is longer than its prompt of {} tokens", + positions.start, + generation_start + ); + } + if generation_start == positions.start && !positions.is_empty() { + bail!( + "the turn's cached prefix holds all of its prompt of {generation_start} tokens, so it \ + samples its first token from a position no receipt covers" + ); + } + Ok(()) +} + +/// What stage 0 knows about a turn's tokens beyond what it recorded. +#[derive(Clone, Debug)] +pub(crate) struct TurnTokens { + /// The first position whose token was sampled: the prompt length. + pub generation_start: u32, + /// The last sampled token, which no ubatch computed. + pub final_token: Option, + /// How many tokens the turn sampled, the final one included. + pub sampled: u32, + /// How the node chose the tokens, as the receipt states it + /// ([`sampler_statement`]). + pub sampler: String, +} + +#[derive(Clone)] +pub struct ReceiptsOptions { + /// Address of this stage's receipts HTTP API. `None` serves none: a + /// single stage whose embedder carries [`client_router`] on its OpenAI + /// surface instead. + pub listen: Option, + /// Permit a non-loopback `listen` address. + pub allow_remote: bool, + /// Receipts API of the next stage, for example `http://127.0.0.1:9502`. + /// `None` reaches the next stage, if there is one, over the binary stage + /// connection ([`downstream`]). + pub downstream: Option, + /// The model the operator claims to serve, named in every receipt. + pub claimed_model: String, + /// Ed25519 seed of the key that signs turn roots. A stage without one + /// signs with a key made at startup. + pub signing_key: Option<[u8; 32]>, +} + +impl std::fmt::Debug for ReceiptsOptions { + /// The signing key is the node's secret: it is never written out. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let signing_key = self.signing_key.map(|_| ""); + f.debug_struct("ReceiptsOptions") + .field("listen", &self.listen) + .field("allow_remote", &self.allow_remote) + .field("downstream", &self.downstream) + .field("claimed_model", &self.claimed_model) + .field("signing_key", &signing_key) + .finish() + } +} + +impl ReceiptsOptions { + /// A stage embedded in a host: it serves no receipts API of its own, + /// since the host carries [`client_router`], and reaches a later stage + /// over the binary stage connection. + pub fn embedded(claimed_model: String, signing_key: Option<[u8; 32]>) -> Self { + Self { + listen: None, + allow_remote: false, + downstream: None, + claimed_model, + signing_key, + } + } +} + +/// The runtime a receipt names. +fn runtime_identity() -> String { + turn::runtime_identity( + skippy_runtime::ABI_VERSION_MAJOR, + skippy_runtime::ABI_VERSION_MINOR, + skippy_runtime::ABI_VERSION_PATCH, + &skippy_runtime::receipt_runtime_source(), + ) +} + +/// Resolves a session id to the turn it computes, or computed last. +pub trait SessionTurns: Send + Sync { + fn turn(&self, session: &str) -> Option; +} + +impl SessionTurns for Mutex { + fn turn(&self, session: &str) -> Option { + lock_runtime(self).receipt_turn(session) + } +} + +/// What a stage replays turns with, and what it holds for that between +/// replays. +trait StageReplayer: Replayer + Send + Sync { + /// Frees what the replayer holds for replays once it has been idle, + /// and returns when to ask again; `None` while it holds nothing. + fn release_idle(&self, _now: Instant) -> Option { + None + } +} + +pub struct StageReceipts { + /// The backend the stage computes on, as its receipts name it. + backend: String, + reports: report_queue::ReportQueue, + replayer: OnceLock>, + /// The receipts of the stages after this one; `None` on the last stage. + downstream: Option>, + limits: ReplyLimits, + claimed_model: String, + signing_key: ed25519_dalek::SigningKey, + /// By receipt id: what became of the turn, and what admitting a + /// challenge of it takes. + kept: Mutex, + /// The receipts connections this stage serves. + connections: Arc, + /// When the next pinned turn's pin runs out, so cells are pinned anew + /// then. + pins_due: Mutex>, + /// The openings and rows requests waiting for the stage. + queue: opening_queue::OpeningQueue, + upkeep: OnceLock, + /// The stage's receipts API, which stops with the stage. + api: OnceLock, +} + +/// How this stage reaches the receipts of the next one: over `url`, its +/// receipts API, when one is given, else over the stage connection when +/// there is a next stage. +fn next_stage( + url: Option<&str>, + config: &StageConfig, +) -> Result>> { + use downstream::{COMMIT_TIMEOUT, OPEN_TIMEOUT}; + Ok(match url { + Some(url) => Some(Box::new(downstream::HttpDownstream::new( + url, + COMMIT_TIMEOUT, + OPEN_TIMEOUT, + )?)), + None if config.downstream.is_some() => Some(Box::new(downstream::StageConnection::new( + config, + COMMIT_TIMEOUT, + OPEN_TIMEOUT, + ))), + None => None, + }) +} + +/// Installs the receipt recorder, attaches receipts to the runtime, and +/// serves the receipts API. +/// +/// A stage no audit covers gets none of that: one with a quantized KV +/// cache ([`kv_cache`]), on a backend without rounding profiles, such as +/// Vulkan or Metal ([`audited_backend`]), or with weights of a type that +/// has no rounding profile on its backend, such as f16 on CUDA +/// ([`audited_weights`]). It issues no receipts and serves as if they were +/// off. The reason is logged here, once. +pub fn start( + options: ReceiptsOptions, + config: &StageConfig, + runtime: Arc>, +) -> Result<()> { + check_listen(&options)?; + // a registry that cannot be read leaves the placement unknown + let block_count = lock_runtime(&runtime).model.block_count(); + let backend = skippy_runtime::backend_devices().map_or_else( + |_| "unknown".to_string(), + |devices| audited_backend::stage_backend(config, &devices, block_count), + ); + let unaudited = kv_cache::unaudited(config) + .or_else(|| audited_backend::unaudited(&backend)) + .or_else(|| audited_weights::unaudited(config, &backend)); + if let Some(reason) = unaudited { + tracing::warn!( + stage = config.stage_index, + "receipts stay off for this stage, which serves without them: {reason}" + ); + // an operator who asked for receipts sees why the stage issues none + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "Receipts stay off for this model stage".to_string(), + context: Some(format!( + "stage_id={} model_id={} reason={reason}", + config.stage_id, config.model_id + )), + }, + ); + return Ok(()); + } + let seed = options.signing_key.unwrap_or_else(|| { + let mut seed = [0u8; 32]; + rand::Rng::fill_bytes(&mut rand::rng(), &mut seed); + seed + }); + let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed); + tracing::info!( + "receipts are signed by node key {}", + hex::encode(signing_key.verifying_key().as_bytes()) + ); + // the residual width, which every stage of the chain shares + let width = lock_runtime(&runtime) + .output_activation_boundary() + .and_then(|boundary| boundary.primary_token_width("output").ok()) + .and_then(|width| usize::try_from(width).ok()); + let receipts = Arc::new(StageReceipts::new( + config.stage_index, + config.layer_start..config.layer_end, + backend, + next_stage(options.downstream.as_deref(), config)?, + options.claimed_model, + signing_key, + ReplyLimits::for_width(width), + )); + { + let mut state = lock_runtime(&runtime); + let replayer = native::NativeReplayer::new( + state.model.receipt_replayer(), + Arc::downgrade(&runtime), + Arc::downgrade(&receipts), + ); + receipts.set_replayer(Box::new(replayer)); + receipts.reports.set_native(state.model.receipt_flusher()); + let streams = state + .model + .receipt_replayer() + .kv_streams() + .context("read how the KV cache lays out its cells")?; + receipts.reports.recorder().set_kv_streams(if streams > 1 { + KvStreams::PerSequence + } else { + KvStreams::Shared + }); + // pins for challenges are a share of a stream's cells: of the pool + // the model allocated, which a pool setting can make smaller than + // the context of every lane together + let pool = state.model.kv_pool_cells().unwrap_or(config.ctx_size); + receipts + .reports + .recorder() + .set_pin_budget(pool / streams.max(1)); + let recurrent = state + .model + .set_receipt_recorder(Arc::new(native::RecorderSink::new(&receipts))) + .context("install the receipt recorder")?; + receipts.reports.recorder().set_recurrent(recurrent); + // the runtime state owns the receipts from here + state.set_receipts(receipts.clone()); + } + receipts.start_upkeep()?; + if let Some(listen) = options.listen { + let listener = std::net::TcpListener::bind(listen) + .with_context(|| format!("bind receipts API on {listen}"))?; + let state = http_api::ApiState::of(&receipts, &runtime); + let api = http_api::spawn_api(listener, http_api::router(state))?; + let _ = receipts.api.set(api); + } + tracing::info!( + "receipts on: api={} stage={} layers={}..{}", + options + .listen + .map_or_else(|| "none".to_owned(), |listen| listen.to_string()), + config.stage_index, + config.layer_start, + config.layer_end + ); + Ok(()) +} + +/// The receipts route a node serves on its OpenAI surface, for clients that +/// reach it only there, such as a Mesh peer: `POST /v1/receipts/open`. +/// It opens only bound receipts, for the one challenge the client's VRF +/// draws, so nobody but the client reads a turn's activations. `None` +/// when the runtime issues no receipts. The routes do not keep the runtime +/// loaded. +pub fn client_router(runtime: &Arc>) -> Option { + let receipts = lock_runtime(runtime).receipts().cloned()?; + Some(http_api::client_routes(http_api::ApiState::of( + &receipts, runtime, + ))) +} + +/// The backend the runtime's receipts name, such as `CPU` or `CUDA0`: the +/// one a client picks rounding profiles by. `None` when the runtime issues +/// no receipts. +pub fn backend_name(runtime: &Arc>) -> Option { + Some(lock_runtime(runtime).receipts()?.backend.clone()) +} + +/// Whether the runtime issues receipts and its stage keeps recurrent state +/// (a hybrid model). Such a stage issues no receipt for a turn that +/// continues a cached prefix, so a caller that owes a receipt for every +/// turn must not offer them. +pub fn keeps_recurrent_state(runtime: &Arc>) -> bool { + lock_runtime(runtime) + .receipts() + .is_some_and(|receipts| receipts.reports.recorder().is_recurrent()) +} + +/// Serves a receipts connection of the stage's binary listener, which an +/// earlier stage opened with `first`, with the receipts the runtime holds +/// now; a runtime that issues none says so once ([`chain_server`]). +pub(crate) fn serve_stage_connection( + runtime: &Mutex, + upstream: std::net::TcpStream, + first: skippy_protocol::binary::StageWireMessage, +) -> Result<()> { + let receipts = lock_runtime(runtime).receipts().cloned(); + chain_server::serve_connection(receipts, runtime, upstream, first) +} + +/// Openings carry prompt-derived activations; refuse a public bind unless +/// the operator asked for it. +fn check_listen(options: &ReceiptsOptions) -> Result<()> { + if let Some(listen) = options.listen + && !listen.ip().is_loopback() + && !options.allow_remote + { + bail!( + "receipts API on {listen} would expose opened activations to the network; \ + bind a loopback address or pass --receipts-allow-remote" + ); + } + Ok(()) +} + +/// The positions a turn receipts: what it recorded, up to the last token it +/// fed. A verify window computes drafts past that when the turn stops inside +/// it, and the turn rejected them. +/// +/// A turn that fed a position it did not record computed a ubatch the +/// recorder could not receipt at its end, such as one of embeddings, and +/// gets no receipt: one that stopped short of the position its last token +/// was sampled from would not show how the node chose it. +fn turn_positions( + recorded: std::ops::Range, + turn: &TurnTokens, +) -> Result> { + let fed_end = turn + .sampled + .checked_sub(1) + .map(|fed| turn.generation_start.saturating_add(fed)); + Ok(match fed_end { + Some(end) if end > recorded.end => bail!( + "the turn fed positions up to {end}, and the stage recorded them up to {} only", + recorded.end + ), + Some(end) if recorded.start < end && end < recorded.end => recorded.start..end, + _ => recorded, + }) +} + +impl StageReceipts { + fn new( + stage_index: u32, + layers: std::ops::Range, + backend: String, + downstream: Option>, + claimed_model: String, + signing_key: ed25519_dalek::SigningKey, + limits: ReplyLimits, + ) -> Self { + Self { + // the last stage, with no stage after it, holds the final layer + reports: report_queue::ReportQueue::new(Arc::new( + Recorder::new(stage_index, layers, backend.clone()) + .holding_output(downstream.is_none()), + )), + backend, + replayer: OnceLock::new(), + downstream, + limits, + claimed_model, + signing_key, + kept: Mutex::new(KeptTurns::default()), + connections: Arc::default(), + pins_due: Mutex::new(None), + queue: opening_queue::OpeningQueue::default(), + upkeep: OnceLock::new(), + api: OnceLock::new(), + } + } + + /// Receipts of a stage with no native recorder, for tests of the code + /// that serves beside them. + #[cfg(test)] + pub(crate) fn for_test(stage_index: u32) -> Self { + Self::new( + stage_index, + 0..1, + "test".into(), + None, + "model.gguf".into(), + ed25519_dalek::SigningKey::from_bytes(&[7; 32]), + ReplyLimits::for_width(None), + ) + } + + fn set_replayer(&self, replayer: Box) { + let _ = self.replayer.set(replayer); + } + + /// Starts the thread of the stage's timed chores, which ends when the + /// receipts are dropped. + fn start_upkeep(self: &Arc) -> Result<()> { + let receipts = Arc::downgrade(self); + let upkeep = upkeep::Upkeep::start(move |now| Some(receipts.upgrade()?.run_upkeep(now))) + .context("spawn receipts upkeep thread")?; + let _ = self.upkeep.set(upkeep); + Ok(()) + } + + fn poke_upkeep(&self) { + if let Some(upkeep) = self.upkeep.get() { + upkeep.poke(); + } + } + + /// The stage's timed chores at `now`; returns when they are next due. + fn run_upkeep(&self, now: Instant) -> Option { + if lock(&self.pins_due).is_some_and(|due| due <= now) { + self.pin_turns(now); + } + let pins = *lock(&self.pins_due); + let scratch = self + .replayer + .get() + .and_then(|replayer| replayer.release_idle(now)); + [pins, scratch].into_iter().flatten().min() + } + + /// A session starts a turn: the recorder is told before the session's + /// first ubatch. The caller holds the stage idle. + pub(crate) fn begin_turn(&self, turn: SessionTurn) { + self.reports.begin_turn(turn.seq, turn.turn); + } + + /// Pins the cells of the turns a client may still challenge at `now`, + /// in place of those pinned before, and notes when the next pin runs + /// out. A stage that cannot pin still opens a turn whose cells nothing + /// wrote since. + /// + /// The upkeep and the commit and open handlers pin concurrently, and + /// each pin replaces the whole native pin set, so the snapshot and its + /// publication run under one lock: an older snapshot published after a + /// newer one would unpin a turn just committed. + fn pin_turns(&self, now: Instant) { + let Some(replayer) = self.replayer.get() else { + return; + }; + let mut pins_due = lock(&self.pins_due); + let recorder = self.reports.recorder(); + let cells = recorder.pinned_cells(now); + match replayer.pin_cells(&cells) { + Ok(()) => tracing::debug!("receipts: {} KV cells pinned", cells.len()), + Err(error) => { + recorder.pins_not_applied(); + tracing::debug!("receipts: cannot pin the cells of recent turns: {error:#}"); + } + } + *pins_due = recorder.next_pin_expiry(now); + } + + /// Pins the cells of this stage's recent turns after a pin was made or + /// given up, before the session that wrote them frees them, so their + /// attention rows stay readable for the challenge window and no longer. + fn pin_recent_turns(&self) { + self.pin_turns(Instant::now()); + // the upkeep pins anew when the next pin runs out + self.poke_upkeep(); + } + + /// Commits a session's turn on this stage and every later one, for the + /// stage before this one, and keeps a record of it to admit challenges + /// by. + fn commit_session( + &self, + sessions: &dyn SessionTurns, + request: &CommitRequest, + ) -> Result> { + if request.receipt_id.len() > admission::MAX_RECEIPT_ID_BYTES { + bail!("the receipt id is longer than a stage keeps"); + } + let turn = sessions + .turn(&request.session) + .with_context(|| format!("no native sequence for session {}", request.session))?; + let client_key = request + .client_key + .as_deref() + .map(vrf::key_from_hex) + .transpose() + .context("the client key of the commit")?; + let id = &request.receipt_id; + let reservation = lock(&self.kept).reserve(id, client_key, Instant::now())?; + let committed = self.commit_chain(request, turn); + let outcome = match &committed { + Ok(_) => Outcome::Committed, + Err(error) => Outcome::Refused(format!("{error:#}")), + }; + let later = later_stages(request, committed.as_deref().unwrap_or_default()); + self.settle(id, reservation, outcome, None, later)?; + committed + } + + /// Settles the record of a turn. A turn whose record cannot be kept has + /// no receipt, so what the stage committed for it is dropped. + fn settle( + &self, + id: &str, + reservation: Reservation, + outcome: Outcome, + turn_root: Option<[u8; 32]>, + later: LaterStages, + ) -> Result<()> { + let settled = + lock(&self.kept).settle(id, reservation, outcome, turn_root, later, Instant::now()); + if let Err(kept_turns::Unsettled::Full(_)) = &settled { + self.forget_turn(id); + } + Ok(settled?) + } + + /// Drops what this stage committed for a turn that got no receipt. + fn forget_turn(&self, receipt_id: &str) { + self.reports.recorder().discard(receipt_id); + self.pin_recent_turns(); + } + + /// Commits this stage and every later one. The later stages' + /// commitments are kept only if they continue this stage's. + fn commit_chain( + &self, + request: &CommitRequest, + turn: SessionTurn, + ) -> Result> { + self.reports.wait_applied(); + let positions = request.position_start..request.position_end; + let committed = self.reports.recorder().commit( + &request.receipt_id, + turn.seq, + turn.turn, + positions.clone(), + ); + let mut stages = vec![committed?]; + // the sequence's next ubatch starts its next turn; a commit that + // failed, such as one forged on the stage port, arms nothing + self.reports.arm_state(turn.seq); + let pinned = self.admit_pin(request); + self.pin_recent_turns(); + pinned?; + if let Some(downstream) = &self.downstream { + let limit = ReplyLimits::commit(positions.end - positions.start); + let later = downstream.commit(request, limit).and_then(|later| { + reply_limits::check_commitments(&stages[0], &later, &positions)?; + Ok(later) + }); + match later { + Ok(later) => stages.extend(later), + Err(error) => { + // no receipt names the turn: nothing will open it + self.forget_turn(&request.receipt_id); + return Err(error); + } + } + } + Ok(stages) + } + + /// Pins the committed turn of `request` while its client can challenge + /// it. Older pins give way when the turn takes its client key or all + /// keys past their share of the cache. A turn nobody can challenge + /// needs no pin. + fn admit_pin(&self, request: &CommitRequest) -> Result<()> { + let recorder = self.reports.recorder(); + let Some(key) = request.client_key.as_deref() else { + recorder.release_pin(&request.receipt_id); + return Ok(()); + }; + let key = vrf::key_from_hex(key).context("the client key of the commit")?; + recorder.admit_pin(&request.receipt_id, key, Instant::now()) + } + + /// Stage 0, after a turn: commits the whole chain and keeps the + /// receipt, or why there is none. + fn finish_turn( + &self, + receipt_id: &str, + session: &str, + session_turn: SessionTurn, + tokens: TurnTokens, + request: Option, + ) -> Result { + let client_key = request.as_ref().map(|request| request.client_key); + let reservation = match lock(&self.kept).reserve(receipt_id, client_key, Instant::now()) { + Ok(reservation) => reservation, + Err(error) => { + // the turn commits nothing; its sequence's next ubatch + // still starts its next turn + self.reports.arm_state(session_turn.seq); + return Err(error); + } + }; + let sampler = tokens.sampler.clone(); + let result = self + .commit_turn(receipt_id, session, session_turn, tokens, client_key) + .map(|mut receipt| { + if let Some(request) = request { + let binding = BindingRequest { + client_key: request.client_key, + parent: request.parent, + runtime: runtime_identity(), + sampler, + }; + turn::bind(&mut receipt, &binding, &self.signing_key); + } + receipt + }); + let (outcome, root, later) = match &result { + Ok(receipt) => { + let root = receipt + .binding + .as_ref() + .and_then(|binding| hex_array(&binding.turn_root, "the turn root").ok()); + let later = LaterStages { + position_start: receipt.position_start, + position_end: receipt.position_end, + commitments: receipt.stages.get(1..).unwrap_or_default().into(), + }; + (Outcome::Issued(Arc::new(receipt.clone())), root, later) + } + Err(error) => ( + Outcome::Refused(format!("{error:#}")), + None, + LaterStages::default(), + ), + }; + self.settle(receipt_id, reservation, outcome, root, later)?; + result + } + + fn commit_turn( + &self, + receipt_id: &str, + session: &str, + session_turn: SessionTurn, + tokens: TurnTokens, + client_key: Option<[u8; 32]>, + ) -> Result { + self.reports.wait_applied(); + let recorder = self.reports.recorder(); + let Some(recorded) = recorder.recorded_range(session_turn.seq, session_turn.turn) else { + // the sequence's next ubatch still starts its next turn + self.reports.arm_state(session_turn.seq); + match recorder.last_error() { + Some(reason) => bail!("the turn recorded nothing: {reason}"), + None => bail!("the turn recorded nothing"), + } + }; + let positions = match turn_positions(recorded, &tokens) { + Ok(positions) => positions, + Err(error) => { + self.reports.arm_state(session_turn.seq); + return Err(error); + } + }; + check_turn_start(tokens.generation_start, &positions)?; + let request = CommitRequest { + receipt_id: receipt_id.to_string(), + session: session.to_string(), + position_start: positions.start, + position_end: positions.end, + client_key: client_key.map(hex::encode), + }; + // a turn that commits nothing still starts its sequence's next turn + let stages = self + .commit_chain(&request, session_turn) + .inspect_err(|_| self.reports.arm_state(session_turn.seq))?; + // a turn that continues a cached prefix receipts only what it computed + let generation_start = tokens + .generation_start + .clamp(positions.start, positions.end); + Ok(Receipt { + version: RECEIPT_VERSION, + receipt_id: receipt_id.to_string(), + model: self.claimed_model.clone(), + position_start: positions.start, + position_end: positions.end, + tokens: recorder.turn_tokens(receipt_id)?, + generation_start, + final_token: tokens.final_token, + stages, + binding: None, + }) + } + + /// An error of the later stages, as this stage passes it on + /// ([`refusal::from_later_stages`]). + fn passed_on(&self, error: anyhow::Error, receipt_id: &str) -> anyhow::Error { + let stage_index = self.reports.recorder().stage_index(); + refusal::from_later_stages(error, receipt_id, stage_index) + } + + fn replayer(&self) -> Result<&dyn Replayer> { + let replayer: &dyn StageReplayer = self + .replayer + .get() + .context("this stage cannot replay turns")? + .as_ref(); + Ok(replayer) + } + + /// Opens the attention rows on this stage and every later one, once the + /// request has its turn at the stage ([`opening_queue`]). + fn rows( + &self, + blocks: &BlockChallenge, + forwarded_opening: Option<[u8; 32]>, + ) -> Result { + let _slot = self.queue.enter(self.queue_key(&blocks.receipt_id)?)?; + self.rows_now(blocks, forwarded_opening) + } + + /// [`Self::rows`] without waiting for a turn, once the request is + /// admitted ([`Self::admit_rows`]). + fn rows_now( + &self, + blocks: &BlockChallenge, + forwarded_opening: Option<[u8; 32]>, + ) -> Result { + let admitted = self.admit_rows(blocks, forwarded_opening)?; + let replayer = self.replayer()?; + self.reports.wait_applied(); + let own = self.reports.recorder().open_rows(blocks, replayer); + // the rows are read: the turn's cells need no pin any more + self.pin_recent_turns(); + let mut stages = vec![own?]; + if let Some(downstream) = &self.downstream { + let request = ForwardedRows { + blocks: blocks.clone(), + opening: admitted.opening.map(hex::encode), + }; + let later = downstream + .rows(&request, self.limits.rows(blocks)) + .map_err(|e| self.passed_on(e, &blocks.receipt_id))?; + if later.receipt_id != blocks.receipt_id { + bail!("the next stage opened rows of another receipt"); + } + let answered = later.stages.iter().map(|stage| stage.stage_index); + reply_limits::check_stages(&admitted.later, answered)?; + stages.extend(later.stages); + } + Ok(RowsOpening { + receipt_id: blocks.receipt_id.clone(), + stages, + }) + } + + /// [`Self::rows`] for the stage before this one over the stage + /// connection. The request had its turn at the first stage, so a later + /// stage does not queue it or turn it away. + fn rows_forwarded(&self, request: &ForwardedRows) -> Result { + let opening = request + .opening + .as_deref() + .map(|digest| hex_array(digest, "the opening digest")) + .transpose()?; + self.rows_now(&request.blocks, opening) + } + + /// Opens the challenge on this stage and every later one, once it has + /// its turn at the stage ([`opening_queue`]). A challenge turned away + /// is not admitted, so the client can send it again. + fn open(&self, challenge: &Challenge, forwarded_root: Option<[u8; 32]>) -> Result { + let key = self.queue_key(&challenge.receipt_id)?; + self.pinned_while_opening(&challenge.receipt_id, || { + let _slot = self.queue.enter(key)?; + self.open_now(challenge, forwarded_root) + }) + } + + /// Runs `open`, an opening of the turn `receipt_id`, with the turn's + /// cells pinned from now until it ends ([`Recorder::hold_for_opening`]). + /// The opening reads the cells after the replay, which takes seconds + /// for a long prompt, and the challenge may wait in the queue first: a + /// pin that ran out meanwhile would let a later request write the cells, + /// and the stage could no longer open a turn it owes an opening. + fn pinned_while_opening( + &self, + receipt_id: &str, + open: impl FnOnce() -> Result, + ) -> Result { + let recorder = self.reports.recorder(); + recorder.hold_for_opening(receipt_id, Instant::now()); + self.pin_recent_turns(); + let opened = open(); + recorder.end_opening(receipt_id); + self.pin_recent_turns(); + opened + } + + /// [`Self::open`] without waiting for a turn, once the challenge is + /// admitted ([`Self::admit_challenge`]): only an admitted challenge is + /// replayed, and counts toward the replays a receipt gets. + fn open_now(&self, challenge: &Challenge, forwarded_root: Option<[u8; 32]>) -> Result { + let admitted = self.admit_challenge(challenge, forwarded_root)?; + let replayer = self.replayer()?; + self.reports.wait_applied(); + let own = self.reports.recorder().open(challenge, replayer); + // an opened turn is pinned for its rows, or not at all + self.pin_recent_turns(); + let mut stages = vec![own?]; + self.mark_opened(&challenge.receipt_id); + if let Some(downstream) = &self.downstream { + let request = ForwardedOpen { + challenge: challenge.clone(), + turn_root: admitted.turn_root.map(hex::encode), + }; + let limit = self.limits.opening(challenge, &admitted.later); + let later = downstream + .open(&request, limit) + .map_err(|e| self.passed_on(e, &challenge.receipt_id))?; + if later.receipt_id != challenge.receipt_id { + bail!("the next stage opened another receipt"); + } + let answered = later.stages.iter().map(|stage| stage.stage_index); + reply_limits::check_stages(&admitted.later, answered)?; + stages.extend(later.stages); + } + Ok(Opening { + receipt_id: challenge.receipt_id.clone(), + stages, + }) + } + + /// [`Self::open`] for the stage before this one over the stage + /// connection. The challenge had its turn at the first stage, so a + /// later stage does not queue it or turn it away. + fn open_forwarded(&self, request: &ForwardedOpen) -> Result { + let root = request + .turn_root + .as_deref() + .map(|root| hex_array(root, "the turn root")) + .transpose()?; + self.pinned_while_opening(&request.challenge.receipt_id, || { + self.open_now(&request.challenge, root) + }) + } +} + +/// The later stages of a committed chain, as this stage keeps them for a +/// request's turn. +fn later_stages(request: &CommitRequest, stages: &[StageCommitment]) -> LaterStages { + LaterStages { + position_start: request.position_start, + position_end: request.position_end, + commitments: stages.get(1..).unwrap_or_default().into(), + } +} + +/// The id a turn's receipt is issued under: the one the client asked for +/// (`x-receipt-id`), else the request's id, else the backend's own. +fn issued_id(asked: Option, frontend: Option<[u8; 16]>, request_id: u64) -> String { + asked + .or(frontend.map(uuid::Uuid::from_bytes)) + .map(|id| id.hyphenated().to_string()) + .unwrap_or_else(|| format!("{request_id:016x}")) +} + +/// Stage 0 hook at the end of a turn, called while the turn's session still +/// holds its sequence. Failures are logged; they never fail the user's +/// request. Returns the receipt when the request asked for a bound one, for +/// the response to carry. +pub(crate) fn finish_stage_zero_turn( + runtime: &Mutex, + frontend_request_id: Option<[u8; 16]>, + receipt_request: Option, + request_id: u64, + session: &str, + tokens: TurnTokens, +) -> Option { + let (receipts, session_turn) = { + let state = lock_runtime(runtime); + let receipts = state.receipts().cloned()?; + (receipts, state.receipt_turn(session)) + }; + let receipt_id = issued_id( + receipt_request.and_then(|request| request.id), + frontend_request_id, + request_id, + ); + let bound = receipt_request.is_some(); + let result = session_turn + .with_context(|| format!("no native sequence for session {session}")) + .and_then(|session_turn| { + receipts.finish_turn(&receipt_id, session, session_turn, tokens, receipt_request) + }); + match result { + Ok(receipt) => { + tracing::info!( + "receipt {} committed: positions {}..{}, {} stages", + receipt.receipt_id, + receipt.position_start, + receipt.position_end, + receipt.stages.len() + ); + bound.then(|| serde_json::to_value(&receipt).ok()).flatten() + } + Err(error) => { + tracing::warn!("receipt {receipt_id} not committed: {error:#}"); + None + } + } +} + +#[cfg(test)] +#[path = "receipts/tests.rs"] +mod tests; + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/crates/skippy-serving/src/receipts/admission.rs b/crates/skippy-serving/src/receipts/admission.rs new file mode 100644 index 00000000..787a818c --- /dev/null +++ b/crates/skippy-serving/src/receipts/admission.rs @@ -0,0 +1,374 @@ +//! Which challenges a stage opens, decided before it replays anything. +//! +//! A stage opens a challenge only of a turn it keeps a record of +//! ([`super::kept_turns`]); any other receipt id is not found, on every +//! route and on the stage connection. The challenge must be one a draw +//! makes: stage 0 checks it against the receipt, every stage against the +//! turn it committed, so an opening costs a bounded replay whoever asks. +//! +//! A turn bound to a client key is opened for one challenge, and only with +//! a VRF proof of its turn root under that key, so the client cannot +//! choose what it challenges and nobody else reads the turn's activations. +//! Stage 0 knows the root from the receipt it signed. A later stage got the +//! client key with the commit and gets the root with the forwarded +//! challenge; it checks the same proof, and holds the turn to the first +//! root a proof was good for. Rows are read the same way: for blocks of an +//! admitted challenge's attention picks, and for a bound turn with the +//! client's proof of the opening they follow. +//! +//! A turn bound to no key has no proof to ask for. It is opened where a +//! stage's own receipts API or the stage before it asks, for at most +//! [`MAX_REPLAYS_PER_RECEIPT`] challenges. + +use std::sync::Arc; +use std::time::Instant; + +use anyhow::{Context, Result, bail}; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::challenge; +use skippy_receipts::commitment::Hash; +use skippy_receipts::recorder::MAX_REPLAYS_PER_RECEIPT; +use skippy_receipts::turn; +use skippy_receipts::vrf; +use skippy_receipts::wire::{Challenge, Receipt}; + +use super::kept_turns::{KeptTurn, LaterStages, Outcome}; +use super::opening_queue::QueueKey; +use super::refusal::{NotFound, not_found}; +use super::{StageReceipts, lock}; + +/// A receipt id a stage keeps a record under, at most this long. Stage 0 +/// makes ids of 36 bytes; a later stage takes them from the stage before. +pub(super) const MAX_RECEIPT_ID_BYTES: usize = 128; +/// Bytes an admitted challenge holds at most, which a stage keeps per turn: +/// its id, its proof, and the picks, head positions and attention picks of +/// a draw. +pub(super) const MAX_ADMITTED_CHALLENGE_BYTES: usize = 1024; + +/// What a stage needs of a challenge it admitted to open it on the stages +/// after it. +pub(super) struct AdmittedChallenge { + /// The turn root the proof is over, for a bound turn. + pub turn_root: Option, + pub later: LaterStages, +} + +/// As [`AdmittedChallenge`], for rows. +pub(super) struct AdmittedRows { + /// The digest of the opening the proof is over, for a bound turn. + pub opening: Option, + pub later: LaterStages, +} + +/// Bytes a kept challenge holds. +fn challenge_bytes(challenge: &Challenge) -> usize { + let picks: usize = challenge + .picks + .iter() + .map(|pick| size_of_val(pick) + pick.positions.len() * size_of::()) + .sum(); + size_of::() + + challenge.receipt_id.len() + + challenge.proof.as_ref().map_or(0, String::len) + + picks + + challenge.head.len() * size_of::() + + size_of_val(challenge.attention.as_slice()) +} + +/// The record of a turn that was committed, or why there is none to open. +fn committed<'a>(kept: Option<&'a KeptTurn>, id: &str) -> Result<&'a KeptTurn> { + let turn = kept.ok_or_else(|| not_found(id))?; + match &turn.outcome { + Outcome::Issued(_) | Outcome::Committed => Ok(turn), + Outcome::Committing => Err(anyhow::Error::new(NotFound(format!( + "receipt {id} is not committed yet" + )))), + Outcome::Refused(reason) => bail!("turn {id} got no receipt: {reason}"), + } +} + +impl StageReceipts { + /// Whether the receipt `id` is bound to a client key. Fails as an + /// opening of it would: not found for an id the stage keeps no record + /// of. + pub(super) fn is_bound(&self, id: &str) -> Result { + let kept = lock(&self.kept); + Ok(committed(kept.get(id), id)?.client_key.is_some()) + } + + /// The client key a request of receipt `id` waits under + /// ([`super::opening_queue`]). Fails as an opening of it would, so a + /// request for an unknown receipt takes no place in the queue. + pub(super) fn queue_key(&self, id: &str) -> Result { + let kept = lock(&self.kept); + Ok(committed(kept.get(id), id)?.client_key) + } + + /// The receipt of a turn, or why it got none; `None` for an id the + /// stage keeps no record of, or whose turn is still being committed. + /// + /// The receipt id is all a caller shows, so a bound receipt comes + /// without the turn's tokens: its client got it whole with the + /// response, and nobody else reads what the client was told. + pub(super) fn receipt(&self, id: &str) -> Option, String>> { + match &lock(&self.kept).get(id)?.outcome { + Outcome::Issued(receipt) if receipt.binding.is_some() => { + let mut redacted = Receipt::clone(receipt); + redacted.tokens.clear(); + redacted.final_token = None; + Some(Ok(Arc::new(redacted))) + } + Outcome::Issued(receipt) => Some(Ok(receipt.clone())), + Outcome::Refused(reason) => Some(Err(reason.clone())), + Outcome::Committing | Outcome::Committed => None, + } + } + + /// Admits `challenge` for a turn this stage committed, before any + /// replay. `forwarded_root` is the turn root the stage before sent + /// along, which a later stage checks a bound turn's proof against. + pub(super) fn admit_challenge( + &self, + challenge: &Challenge, + forwarded_root: Option, + ) -> Result { + let id = &challenge.receipt_id; + let (receipt, client_key, known_root) = { + let kept = lock(&self.kept); + let turn = committed(kept.get(id), id)?; + let receipt = match &turn.outcome { + Outcome::Issued(receipt) => Some(receipt.clone()), + _ => None, + }; + (receipt, turn.client_key, turn.turn_root) + }; + // the size of the challenge first: nothing here costs more than a + // few hashes until it is known to ask for a draw's worth + if let Some(receipt) = &receipt { + challenge::check_shape(challenge, receipt)?; + } + self.reports.recorder().check_challenge(challenge)?; + if challenge_bytes(challenge) > MAX_ADMITTED_CHALLENGE_BYTES { + bail!("the challenge holds more than a draw and its proof"); + } + let root = match client_key { + Some(key) => { + let proof = challenge.proof.as_deref().context( + "the receipt is bound to a client key; the challenge needs its VRF proof", + )?; + let root = known_root.or(forwarded_root).context( + "the receipt is bound to a client key; the challenge needs the turn root \ + its proof is over", + )?; + if forwarded_root.is_some_and(|forwarded| forwarded != root) { + bail!("the challenge names another turn root than the receipt's"); + } + vrf::verify( + &key, + &turn::challenge_input(&root), + &vrf::proof_from_hex(proof)?, + ) + .context("the challenge's VRF proof")?; + Some(root) + } + None => None, + }; + let mut kept = lock(&self.kept); + let turn = kept.get_mut(id).ok_or_else(|| not_found(id))?; + if turn.client_key != client_key || turn.turn_root != known_root { + bail!("receipt {id} names another turn since the challenge arrived"); + } + let limit = match client_key { + Some(_) => 1, + None => MAX_REPLAYS_PER_RECEIPT as usize, + }; + if !turn.admit(challenge, limit, Instant::now()) { + bail!("receipt {id} was already challenged"); + } + turn.turn_root = turn.turn_root.or(root); + Ok(AdmittedChallenge { + turn_root: root, + later: turn.later.clone(), + }) + } + + /// Admits `blocks` for a turn this stage opened, before any row is + /// read. `forwarded_opening` is the digest of the opening stage 0 + /// signed, as the stage before sent it along. + pub(super) fn admit_rows( + &self, + blocks: &BlockChallenge, + forwarded_opening: Option, + ) -> Result { + let id = &blocks.receipt_id; + let mut kept = lock(&self.kept); + let turn = kept.get_mut(id).ok_or_else(|| not_found(id))?; + committed(Some(&*turn), id)?; + let Some(first) = turn.challenges.first() else { + bail!("receipt {id} was not opened"); + }; + if !turn + .challenges + .iter() + .any(|admitted| blocks.check_shape(admitted).is_ok()) + { + blocks.check_shape(first)?; + bail!("the rows ask for blocks of no challenge that was opened"); + } + let opening = match turn.client_key { + Some(key) => { + let issued = matches!(turn.outcome, Outcome::Issued(_)); + // stage 0 signed the opening itself; a later stage is told + // which one the proof is over + let opened = turn + .opened + .or(forwarded_opening.filter(|_| !issued)) + .with_context(|| format!("receipt {id} was not opened"))?; + if forwarded_opening.is_some_and(|forwarded| forwarded != opened) { + bail!("the rows follow another opening than the one this stage knows"); + } + let proof = blocks + .proof + .as_deref() + .context("the receipt is bound to a client key; the rows need its VRF proof")?; + vrf::verify( + &key, + &turn::rows_input_of_digest(&opened), + &vrf::proof_from_hex(proof)?, + ) + .context("the rows' VRF proof")?; + turn.opened = Some(opened); + Some(opened) + } + None => None, + }; + Ok(AdmittedRows { + opening, + later: turn.later.clone(), + }) + } + + /// Notes that this stage opened a turn, so its record is kept while the + /// client may ask for the rows. + pub(super) fn mark_opened(&self, id: &str) { + if let Some(turn) = lock(&self.kept).get_mut(id) { + turn.mark_opened(None, Instant::now()); + } + } + + /// The root of a bound receipt this stage issued and signs for. + fn signed_root(&self, id: &str) -> Option { + let kept = lock(&self.kept); + let turn = kept.get(id)?; + match (&turn.outcome, turn.client_key) { + (Outcome::Issued(_), Some(_)) => turn.turn_root, + _ => None, + } + } + + /// Stage 0's signature of its opening of `challenge`, for a bound + /// receipt it issued. The rows' proof is over the opening signed last. + pub(super) fn sign_opening( + &self, + challenge: &Challenge, + bytes: &[u8], + ) -> Result> { + let id = &challenge.receipt_id; + let Some(root) = self.signed_root(id) else { + return Ok(None); + }; + if let Some(turn) = lock(&self.kept).get_mut(id) { + turn.mark_opened(Some(*blake3::hash(bytes).as_bytes()), Instant::now()); + } + Ok(Some(turn::sign_opening( + &self.signing_key, + &root, + challenge, + bytes, + ))) + } + + /// Stage 0's signature of the attention rows it opened for `blocks`, + /// for a bound receipt it issued. + pub(super) fn sign_rows( + &self, + blocks: &BlockChallenge, + bytes: &[u8], + ) -> Result> { + let Some(root) = self.signed_root(&blocks.receipt_id) else { + return Ok(None); + }; + Ok(Some(turn::sign_rows( + &self.signing_key, + &root, + blocks, + bytes, + ))) + } + + /// Stage 0's signature of its answer that the chain can no longer open + /// `request`, the digest of a challenge or block challenge, for a bound + /// receipt it issued. + pub(super) fn sign_cannot_open( + &self, + id: &str, + request: &Hash, + bytes: &[u8], + ) -> Option { + let root = self.signed_root(id)?; + Some(turn::sign_cannot_open( + &self.signing_key, + &root, + request, + bytes, + )) + } +} + +#[cfg(test)] +mod tests { + use skippy_receipts::attention::opening::AttentionPick; + use skippy_receipts::challenge::{ + ATTENTION_POSITIONS_PER_LAYER, HEAD_POSITIONS, LAYERS_PER_CHALLENGE, POSITIONS_PER_LAYER, + }; + use skippy_receipts::wire::Pick; + + use super::*; + + // A stage keeps a clone of each challenge it admits; the largest one a + // draw makes fits the bound it holds them to. + #[test] + fn the_largest_challenge_a_draw_makes_fits_what_a_stage_keeps() { + let picks: Vec = (0..LAYERS_PER_CHALLENGE as u32) + .map(|layer| Pick { + layer, + positions: (0..POSITIONS_PER_LAYER as u32).collect(), + }) + .collect(); + let attention = picks + .iter() + .flat_map(|pick| { + pick.positions + .iter() + .take(ATTENTION_POSITIONS_PER_LAYER) + .map(|&position| AttentionPick { + position, + layer: pick.layer, + head_draw: u32::MAX, + }) + }) + .collect(); + let largest = Challenge { + receipt_id: "r".repeat(MAX_RECEIPT_ID_BYTES), + picks, + proof: Some("0".repeat(2 * vrf::PROOF_LEN)), + head: (0..HEAD_POSITIONS as u32).collect(), + attention, + }; + let bytes = challenge_bytes(&largest); + assert!(bytes <= MAX_ADMITTED_CHALLENGE_BYTES, "{bytes}"); + let mut longer = largest; + longer.proof = Some("0".repeat(MAX_ADMITTED_CHALLENGE_BYTES)); + assert!(challenge_bytes(&longer) > MAX_ADMITTED_CHALLENGE_BYTES); + } +} diff --git a/crates/skippy-serving/src/receipts/audited_backend.rs b/crates/skippy-serving/src/receipts/audited_backend.rs new file mode 100644 index 00000000..f9cd515e --- /dev/null +++ b/crates/skippy-serving/src/receipts/audited_backend.rs @@ -0,0 +1,310 @@ +//! Whether a stage runs on a backend an audit covers. +//! +//! An audit checks a stage's matrix products against the rounding of its +//! backend, and has measured profiles for CPU and CUDA alone +//! ([`skippy_receipts::rounding_profiles::BackendFamily`]). On any other backend +//! (Vulkan, Metal, ROCm) a stage issues no receipts: an honest Vulkan node +//! with K-quant weights failed most audits, and Metal's prefill fits no +//! profile. So its recorder does not start, which also spares it the cost +//! of recording, the stage serves every request as usual, and an embedder +//! that asks whether the runtime issues receipts hears that it issues +//! none. + +use skippy_protocol::StageConfig; +use skippy_receipts::rounding_profiles::BackendFamily; +use skippy_runtime::{BackendDevice, BackendDeviceType}; + +/// The backend the stage's matrix products run on, named as its device is. +/// +/// It follows the stage's own placement, not the first device the runtime +/// registered, and names a backend an audit covers only when every product +/// of the stage runs there: +/// +/// - On the CPU (a selected CPU device, no offloaded layers, or no GPU), +/// no other backend may take a product: llama.cpp hands host-weight +/// products to an accelerator such as BLAS whenever one is registered, +/// and offloads large batches of them to a GPU unless `op_offload` is +/// off. +/// - On a GPU, selected or not, every layer of the stage must be offloaded +/// ([`offloads_every_layer`]) with no routed experts kept in host +/// memory: selecting a device does not offload a layer to it. The GPUs +/// llama.cpp picks must share one audited family. +/// +/// Any other placement gets a name no audit covers, so the stage issues no +/// receipts. `block_count` is the model's layer count, which llama.cpp +/// counts `n_gpu_layers` against. +pub(super) fn stage_backend( + config: &StageConfig, + devices: &[BackendDevice], + block_count: Option, +) -> String { + let of_type = |kind: BackendDeviceType| -> Vec<&str> { + devices + .iter() + .filter(|device| device.device_type == kind) + .map(|device| device.name.as_str()) + .collect() + }; + // llama.cpp offloads to its discrete GPUs, or its integrated ones if none + let mut gpus = of_type(BackendDeviceType::Gpu); + if gpus.is_empty() { + gpus = of_type(BackendDeviceType::IntegratedGpu); + } + let on_cpu = || { + let accelerators = of_type(BackendDeviceType::Accelerator); + if !accelerators.is_empty() { + format!("CPU+{} (accelerator)", accelerators.join("+")) + } else if !gpus.is_empty() && config.op_offload != Some(false) { + format!("CPU+{} (operation offload)", gpus.join("+")) + } else { + "CPU".to_string() + } + }; + let on_gpu = |gpu: &str| { + if !offloads_every_layer(config, block_count) { + // the stage's layers may sit on both the CPU and the GPU + format!( + "CPU+{gpu} (partial offload of {} layers)", + config.n_gpu_layers + ) + } else if config.host_expert_layers.is_some() { + format!("CPU+{gpu} (routed experts in host memory)") + } else { + gpu.to_string() + } + }; + if let Some(device) = &config.selected_device { + let name = device.backend_device.as_str(); + return if name.eq_ignore_ascii_case("CPU") || name.eq_ignore_ascii_case("CPU0") { + // no layer is offloaded, but the model keeps every GPU, which + // operation offload can reach + on_cpu() + } else { + on_gpu(name) + }; + } + let Some(first) = gpus.first().copied() else { + return on_cpu(); + }; + if config.n_gpu_layers == 0 { + return on_cpu(); + } + let family = BackendFamily::of(first); + if gpus.len() == 1 + || family.is_some() && gpus.iter().all(|gpu| BackendFamily::of(gpu) == family) + { + on_gpu(first) + } else { + format!("mixed {}", gpus.join("+")) + } +} + +/// Whether `n_gpu_layers` puts every layer of the stage on a GPU. +/// +/// llama.cpp numbers the model's layers `0..=block_count`, the output +/// layer last, and offloads the last `n_gpu_layers` of them; a negative +/// count offloads all. So the stage's layers from `layer_start` on are all +/// offloaded when `n_gpu_layers >= block_count + 1 - layer_start`. A count +/// such as 99 that operators use for "everything" is thus a full offload, +/// and an unknown `block_count` counts as a partial one. +fn offloads_every_layer(config: &StageConfig, block_count: Option) -> bool { + let Ok(count) = u32::try_from(config.n_gpu_layers) else { + return true; + }; + block_count + .is_some_and(|blocks| u64::from(count) + u64::from(config.layer_start) > u64::from(blocks)) +} + +/// Why a stage on `backend` issues no receipts, when it issues none. +pub(super) fn unaudited(backend: &str) -> Option { + BackendFamily::of(backend).is_none().then(|| { + format!("the stage runs on backend {backend}, and an audit covers CPU and CUDA alone") + }) +} + +#[cfg(test)] +mod tests { + use skippy_protocol::{StageConfig, StageDevice}; + use skippy_runtime::{BackendDevice, BackendDeviceType}; + + use super::unaudited; + + /// The layers of the model the stages below serve. + const BLOCKS: Option = Some(36); + + /// The backend of a stage of that model. + fn stage_backend(config: &StageConfig, devices: &[BackendDevice]) -> String { + super::stage_backend(config, devices, BLOCKS) + } + + fn device(name: &str, device_type: BackendDeviceType) -> BackendDevice { + BackendDevice { + name: name.to_string(), + description: None, + device_id: None, + memory_free: 0, + memory_total: 0, + device_type, + caps: 0, + } + } + + fn placed(n_gpu_layers: i32, selected: Option<&str>) -> StageConfig { + StageConfig { + n_gpu_layers, + selected_device: selected.map(|name| StageDevice { + backend_device: name.to_string(), + stable_id: None, + index: None, + vram_bytes: None, + }), + ..StageConfig::default() + } + } + + /// `placed`, with operation offload turned off. + fn kept(n_gpu_layers: i32, selected: Option<&str>) -> StageConfig { + StageConfig { + op_offload: Some(false), + ..placed(n_gpu_layers, selected) + } + } + + #[test] + fn the_backend_is_where_the_stage_runs_not_the_first_device() { + use BackendDeviceType::{Cpu, Gpu, IntegratedGpu}; + // a CPU registered first does not make a CUDA stage a CPU one + let cuda = [ + device("CPU", Cpu), + device("CUDA0", Gpu), + device("CUDA1", Gpu), + ]; + assert_eq!(stage_backend(&placed(-1, None), &cuda), "CUDA0"); + assert_eq!(stage_backend(&placed(-1, Some("CUDA1")), &cuda), "CUDA1"); + // nor does a CUDA registered first make a CPU stage a CUDA one + let gpu_first = [device("CUDA0", Gpu), device("CPU", Cpu)]; + assert_eq!(stage_backend(&kept(0, None), &gpu_first), "CPU"); + assert_eq!(stage_backend(&kept(-1, Some("CPU0")), &gpu_first), "CPU"); + assert_eq!(stage_backend(&kept(-1, Some("cpu")), &gpu_first), "CPU"); + let cpu_only = [device("CPU", Cpu)]; + assert_eq!(stage_backend(&placed(-1, None), &cpu_only), "CPU"); + assert_eq!(stage_backend(&placed(0, Some("CPU")), &cpu_only), "CPU"); + let metal = [device("MTL0", IntegratedGpu), device("CPU", Cpu)]; + assert_eq!(stage_backend(&placed(-1, None), &metal), "MTL0"); + assert!(unaudited(&stage_backend(&placed(-1, None), &metal)).is_some()); + } + + #[test] + fn a_placement_that_can_mix_backends_gets_no_receipts() { + use BackendDeviceType::{Cpu, Gpu}; + let cuda = [device("CPU", Cpu), device("CUDA0", Gpu)]; + let partial = stage_backend(&placed(12, None), &cuda); + assert!(unaudited(&partial).is_some(), "{partial}"); + let mixed = [ + device("CUDA0", Gpu), + device("Vulkan0", Gpu), + device("CPU", Cpu), + ]; + let both = stage_backend(&placed(-1, None), &mixed); + assert_eq!(both, "mixed CUDA0+Vulkan0"); + assert!(unaudited(&both).is_some()); + } + + /// Selecting a GPU does not offload a layer to it: the stage runs there + /// only with every layer offloaded, and no routed experts on the host. + #[test] + fn a_selected_gpu_runs_the_stage_only_with_every_layer_offloaded() { + use BackendDeviceType::{Cpu, Gpu}; + let cuda = [device("CPU", Cpu), device("CUDA0", Gpu)]; + assert_eq!(stage_backend(&placed(-1, Some("CUDA0")), &cuda), "CUDA0"); + for layers in [0, 1, 12, 36] { + let backend = stage_backend(&placed(layers, Some("CUDA0")), &cuda); + assert!(unaudited(&backend).is_some(), "{layers}: {backend}"); + } + // a count that covers every layer is an offload of every layer + assert_eq!(stage_backend(&placed(999, Some("CUDA0")), &cuda), "CUDA0"); + let experts = |selected| StageConfig { + host_expert_layers: Some(skippy_protocol::HostExpertLayers { start: 0, end: 4 }), + ..placed(-1, selected) + }; + for selected in [Some("CUDA0"), None] { + let backend = stage_backend(&experts(selected), &cuda); + assert!(unaudited(&backend).is_some(), "{selected:?}: {backend}"); + } + } + + /// llama.cpp gives host-weight products to a registered accelerator + /// (BLAS), and large batches of them to a GPU unless operation offload + /// is off: neither runs with the CPU's rounding. + #[test] + fn a_cpu_stage_whose_products_can_leave_the_cpu_gets_no_receipts() { + use BackendDeviceType::{Accelerator, Cpu, Gpu}; + let blas = [device("BLAS", Accelerator), device("CPU", Cpu)]; + for config in [placed(0, None), placed(-1, None), kept(0, Some("CPU"))] { + let backend = stage_backend(&config, &blas); + assert!(unaudited(&backend).is_some(), "{backend}"); + assert!(backend.contains("BLAS"), "{backend}"); + } + let cuda = [device("CPU", Cpu), device("CUDA0", Gpu)]; + for config in [ + placed(0, None), + placed(0, Some("CPU0")), + StageConfig { + op_offload: Some(true), + ..placed(0, None) + }, + ] { + let backend = stage_backend(&config, &cuda); + assert!(unaudited(&backend).is_some(), "{backend}"); + } + assert_eq!(stage_backend(&kept(0, Some("CPU0")), &cuda), "CPU"); + assert_eq!( + stage_backend(&placed(0, None), &[device("CPU", Cpu)]), + "CPU" + ); + } + + #[test] + fn a_count_that_offloads_every_layer_of_the_stage_is_a_full_offload() { + use BackendDeviceType::{Cpu, Gpu}; + let cuda = [device("CPU", Cpu), device("CUDA0", Gpu)]; + let backend = |n_gpu_layers, layer_start| { + let config = StageConfig { + layer_start, + ..placed(n_gpu_layers, None) + }; + stage_backend(&config, &cuda) + }; + // the counts operators use for "everything" + for count in [-1, 99, 999, i32::MAX] { + assert_eq!(backend(count, 0), "CUDA0", "{count}"); + assert_eq!(backend(count, 18), "CUDA0", "{count}"); + } + // 37 layers with the output: the first stage needs all 37 + assert_eq!(backend(37, 0), "CUDA0"); + let below = backend(36, 0); + assert_eq!(below, "CPU+CUDA0 (partial offload of 36 layers)"); + assert!(unaudited(&below).is_some()); + // the second stage, layers 18 to 35, needs 19: its 18 and the output + assert_eq!(backend(19, 18), "CUDA0"); + assert!(unaudited(&backend(18, 18)).is_some()); + assert!(unaudited(&backend(10, 18)).is_some()); + // a model whose layer count is unknown is not judged offloaded + let unknown = super::stage_backend(&placed(99, None), &cuda, None); + assert!(unaudited(&unknown).is_some(), "{unknown}"); + } + + #[test] + fn only_a_backend_with_rounding_profiles_gets_receipts() { + for backend in ["CPU", "CUDA0", "CUDA1"] { + assert_eq!(unaudited(backend), None, "{backend}"); + } + for backend in [ + "Vulkan0", "Vulkan1", "Metal", "MTL0", "ROCm0", "unknown", "", + ] { + let reason = unaudited(backend).unwrap(); + assert!(reason.contains("CPU and CUDA alone"), "{backend}: {reason}"); + } + assert!(unaudited("Vulkan0").unwrap().contains("backend Vulkan0")); + } +} diff --git a/crates/skippy-serving/src/receipts/audited_weights.rs b/crates/skippy-serving/src/receipts/audited_weights.rs new file mode 100644 index 00000000..a461b901 --- /dev/null +++ b/crates/skippy-serving/src/receipts/audited_weights.rs @@ -0,0 +1,166 @@ +//! Whether an audit can check the weights a stage multiplies. +//! +//! An audit checks a stage's matrix products with the rounding profile of +//! its backend for each weight type +//! ([`skippy_receipts::rounding_profiles::profiles_for`]), and a pair +//! without a profile makes every audit of the stage end as no audit: f16 +//! and bf16 weights on CUDA, for example, or Q4_1 anywhere. A stage that +//! issued receipts for such a model would look audited to a client that +//! asks for receipts, and never be. So it issues none, as on a backend no +//! audit covers ([`super::audited_backend`]). +//! +//! The stage reads the types from the tensor directories of its GGUF +//! files, which costs a header read per file. It checks the matrices of +//! its own layers, as a client does, and the output head on the final +//! stage. A model whose files it cannot read that way (a checkpoint that +//! is not a GGUF) keeps its receipts, and the client's coverage check +//! decides. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use skippy_protocol::StageConfig; +use skippy_receipts::rounding_profiles::{BackendFamily, unprofiled}; + +/// A tensor of the stage's files, as far as its type matters here. +struct Weight { + name: String, + layer: Option, + ggml_type: u32, +} + +/// Why a stage of `config` on `backend` issues no receipts, when an audit +/// cannot check its weights. +pub(super) fn unaudited(config: &StageConfig, backend: &str) -> Option { + let family = BackendFamily::of(backend)?; + let tensors = match stage_tensors(config) { + Ok(tensors) => tensors, + Err(error) => { + tracing::debug!( + stage = config.stage_index, + "the stage's weight types are unknown, so the audit decides: {error:#}" + ); + return None; + } + }; + let holds_head = config.downstream.is_none(); + let reason = unprofiled( + family, + multiplied(&tensors, config.layer_start..config.layer_end, holds_head), + )?; + Some(format!("{reason}, so no audit can check this stage")) +} + +/// The tensor directory of the stage's GGUF files. +fn stage_tensors(config: &StageConfig) -> Result> { + let files: Vec = if config.model_part_paths.is_empty() { + let path = config + .model_path + .as_deref() + .context("the stage names no model file")?; + skippy_runtime::gguf_shard_paths(Path::new(path))? + } else { + config.model_part_paths.iter().map(PathBuf::from).collect() + }; + let mut tensors = Vec::new(); + for file in files { + let info = skippy_runtime::ModelInfo::open(&file) + .with_context(|| format!("read the tensors of {}", file.display()))?; + tensors.extend(info.tensors()?.into_iter().map(|t| Weight { + name: t.name, + layer: t.layer_index, + ggml_type: t.ggml_type, + })); + } + Ok(tensors) +} + +/// The weights of `tensors` a stage of `layers` multiplies, as a client +/// checks them: every weight of its layers (a vector among them, such as +/// a norm, is f32 in a GGUF, which has a profile on every backend), and +/// the output head when the stage holds it (`output.weight`, else the +/// token embeddings of a tied head). +fn multiplied( + tensors: &[Weight], + layers: std::ops::Range, + holds_head: bool, +) -> impl Iterator { + let head = ["output.weight", "token_embd.weight"] + .into_iter() + .find_map(|name| tensors.iter().find(|t| t.name == name)) + .filter(|_| holds_head); + tensors + .iter() + .filter(move |t| { + t.name.ends_with(".weight") && t.layer.is_some_and(|l| layers.contains(&l)) + }) + .chain(head) + .map(|t| (t.name.as_str(), t.ggml_type)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const F32: u32 = 0; + const F16: u32 = 1; + const Q8_0: u32 = 8; + + fn tensor(name: &str, layer: Option, ggml_type: u32) -> Weight { + Weight { + name: name.into(), + layer, + ggml_type, + } + } + + fn reason(tensors: &[Weight], family: BackendFamily, holds_head: bool) -> Option { + unprofiled(family, multiplied(tensors, 0..2, holds_head)) + } + + #[test] + fn f16_weights_on_cuda_stop_receipts_and_on_the_cpu_do_not() { + let f16 = [ + tensor("token_embd.weight", None, F16), + tensor("blk.0.attn_norm.weight", Some(0), F32), + tensor("blk.0.attn_q.weight", Some(0), F16), + tensor("blk.1.attn_q.weight", Some(1), F16), + ]; + let why = reason(&f16, BackendFamily::Cuda, false).unwrap(); + assert!(why.contains("f16 weights (blk.0.attn_q.weight)"), "{why}"); + assert_eq!(reason(&f16, BackendFamily::Cpu, true), None); + } + + #[test] + fn only_the_stage_layers_and_its_head_count() { + let tensors = [ + tensor("token_embd.weight", None, Q8_0), + tensor("blk.1.attn_q.weight", Some(1), Q8_0), + // a later stage's layer + tensor("blk.2.attn_q.weight", Some(2), F16), + tensor("output.weight", None, F16), + ]; + assert_eq!(reason(&tensors, BackendFamily::Cuda, false), None); + let why = reason(&tensors, BackendFamily::Cuda, true).unwrap(); + assert!(why.contains("(output.weight)"), "{why}"); + // a tied head is the token embeddings + let tied = [ + tensor("token_embd.weight", None, F16), + tensor("blk.0.attn_q.weight", Some(0), Q8_0), + ]; + assert_eq!(reason(&tied, BackendFamily::Cuda, false), None); + let why = reason(&tied, BackendFamily::Cuda, true).unwrap(); + assert!(why.contains("(token_embd.weight)"), "{why}"); + } + + #[test] + fn a_stage_without_readable_weights_keeps_its_receipts() { + let config = StageConfig { + model_path: Some("/nonexistent/model.safetensors".into()), + ..StageConfig::default() + }; + assert_eq!(unaudited(&config, "CUDA0"), None); + // a backend no audit covers is said by `audited_backend` + assert_eq!(unaudited(&config, "Vulkan0"), None); + } +} diff --git a/crates/skippy-serving/src/receipts/chain_server.rs b/crates/skippy-serving/src/receipts/chain_server.rs new file mode 100644 index 00000000..0ba1e747 --- /dev/null +++ b/crates/skippy-serving/src/receipts/chain_server.rs @@ -0,0 +1,262 @@ +//! Serves the receipts connections the stage before this one opens on the +//! binary stage listener ([`super::downstream`]). +//! +//! Anything that reaches the stage port can open such a connection, so it +//! gets little for free: a stage with receipts off answers once that it +//! has none and hangs up; a stage serves a few receipts connections at a +//! time; a connection that sends nothing for a while is closed, and so is +//! the one that waited longest for a request when a new connection finds +//! every slot held; and a request is admitted like one on the HTTP API, a +//! bound turn only with its client's proof ([`super::admission`]). +//! +//! The stage port does not authenticate its peer: that is out of scope +//! here, and an operator keeps the port to the stages of the pipeline. What +//! a peer that reaches it can still do is described in the receipts +//! design document. + +use std::io::Write; +use std::net::{Shutdown, TcpStream}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use skippy_protocol::binary::{ + ReceiptsReply, StageWireMessage, WireMessageKind, read_stage_message, send_receipts_reply, +}; + +use super::downstream::ChainRequest; +use super::refusal::{self, Unavailable}; +use super::{SessionTurns, StageReceipts}; + +/// Receipts connections a stage serves at once. The stage before it keeps +/// two, and opens two more when one breaks mid-request. +pub(super) const RECEIPTS_CONNECTIONS: usize = 8; +/// A receipts connection that sends no request for this long is closed. +/// The stage before opens another when it next needs one. +const IDLE_TIMEOUT: Duration = Duration::from_secs(120); +/// A reply the stage before does not take in this long ends the connection. +const WRITE_TIMEOUT: Duration = Duration::from_secs(30); +/// How often a connection that waits for a request looks whether it lost +/// its slot. A shutdown from another thread ends a blocked read on some +/// platforms and not on others, so the wait does not rely on it. +const SLOT_CHECK: Duration = Duration::from_millis(200); + +/// The receipts connections a stage serves. +#[derive(Default)] +pub(super) struct ConnectionSlots(Mutex); + +#[derive(Default)] +struct Connections { + held: Vec, + next_id: u64, +} + +struct Held { + id: u64, + /// Since when the connection waits for a request; `None` while it is + /// answering one. + idle_since: Option, + /// A handle that closes the connection. + stream: TcpStream, +} + +/// One served connection; frees its slot when dropped. +struct Slot { + slots: Arc, + id: u64, +} + +impl ConnectionSlots { + fn lock(&self) -> MutexGuard<'_, Connections> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// A slot for the connection `stream`. When every slot is held, the + /// connection that has waited longest for a request is closed for it, + /// so connections that only hold a slot cannot keep out the stage + /// before; `None` when every connection is answering a request. + fn acquire(self: &Arc, stream: &TcpStream) -> Result> { + let stream = stream.try_clone()?; + let mut connections = self.lock(); + if connections.held.len() >= RECEIPTS_CONNECTIONS { + let Some(oldest) = connections + .held + .iter() + .enumerate() + .filter_map(|(i, held)| Some((held.idle_since?, i))) + .min() + .map(|(_, i)| i) + else { + return Ok(None); + }; + let evicted = connections.held.swap_remove(oldest); + // its peer sees the end at once; its own wait sees the lost + // slot at its next look ([`wait_for_request`]) + let _ = evicted.stream.shutdown(Shutdown::Both); + } + let id = connections.next_id; + connections.next_id += 1; + connections.held.push(Held { + id, + idle_since: None, + stream, + }); + Ok(Some(Slot { + slots: self.clone(), + id, + })) + } + + #[cfg(test)] + pub(super) fn held(&self) -> usize { + self.lock().held.len() + } +} + +impl Slot { + /// Notes whether the connection waits for a request. + fn set_idle(&self, idle: bool) { + let mut connections = self.slots.lock(); + if let Some(held) = connections.held.iter_mut().find(|h| h.id == self.id) { + held.idle_since = idle.then(Instant::now); + } + } +} + +impl Slot { + /// Whether the connection still has its slot; not once a newer + /// connection took it. + fn held(&self) -> bool { + let connections = self.slots.lock(); + connections.held.iter().any(|held| held.id == self.id) + } +} + +impl Drop for Slot { + fn drop(&mut self) { + self.slots.lock().held.retain(|held| held.id != self.id); + } +} + +/// Serves a receipts connection that an earlier stage opened with `first`, +/// until that stage closes it or stops using it. +pub(crate) fn serve_connection( + receipts: Option>, + sessions: &dyn SessionTurns, + upstream: TcpStream, + first: StageWireMessage, +) -> Result<()> { + serve_connection_until_idle(receipts, sessions, upstream, first, IDLE_TIMEOUT) +} + +pub(super) fn serve_connection_until_idle( + receipts: Option>, + sessions: &dyn SessionTurns, + mut upstream: TcpStream, + first: StageWireMessage, + idle: Duration, +) -> Result<()> { + upstream.set_write_timeout(Some(WRITE_TIMEOUT))?; + let Some(receipts) = receipts else { + // the stage before learns it once, and asks no more + let off = ReceiptsReply::Unavailable("this stage issues no receipts".to_owned()); + return send(&mut upstream, &off); + }; + let Some(slot) = receipts.connections.acquire(&upstream)? else { + let full = ReceiptsReply::Refused(format!( + "this stage is answering requests on {RECEIPTS_CONNECTIONS} receipts connections" + )); + return send(&mut upstream, &full); + }; + // the connection must not keep an unloaded stage's receipts alive + let receipts = { + let weak = Arc::downgrade(&receipts); + drop(receipts); + weak + }; + let mut message = first; + loop { + send(&mut upstream, &answer(&receipts, sessions, &message))?; + slot.set_idle(true); + if !wait_for_request(&upstream, &slot, idle)? { + return Ok(()); + } + upstream.set_read_timeout(Some(idle))?; + message = match read_stage_message(&mut upstream, 0) { + Ok(message) => message, + Err(error) if closed_or_idle(&error) => return Ok(()), + Err(error) => return Err(error.into()), + }; + slot.set_idle(false); + } +} + +/// Waits until the stage before sends its next request. `false` when the +/// connection ended instead: the peer closed it, it sent nothing for +/// `idle`, or a newer connection took its slot. +fn wait_for_request(upstream: &TcpStream, slot: &Slot, idle: Duration) -> Result { + let waiting_since = Instant::now(); + let mut first_byte = [0u8; 1]; + loop { + let left = idle.saturating_sub(waiting_since.elapsed()); + if left.is_zero() || !slot.held() { + return Ok(false); + } + upstream.set_read_timeout(Some(left.min(SLOT_CHECK)))?; + match upstream.peek(&mut first_byte) { + Ok(0) => return Ok(false), + Ok(_) => return Ok(true), + Err(error) if timed_out(&error) => {} + Err(error) if closed_or_idle(&error) => return Ok(false), + Err(error) => return Err(error.into()), + } + } +} + +fn timed_out(error: &std::io::Error) -> bool { + use std::io::ErrorKind::{TimedOut, WouldBlock}; + matches!(error.kind(), TimedOut | WouldBlock) +} + +fn closed_or_idle(error: &std::io::Error) -> bool { + use std::io::ErrorKind::{TimedOut, UnexpectedEof, WouldBlock}; + matches!(error.kind(), UnexpectedEof | TimedOut | WouldBlock) +} + +fn send(upstream: &mut TcpStream, reply: &ReceiptsReply) -> Result<()> { + send_receipts_reply(&mut *upstream, reply)?; + upstream.flush()?; + Ok(()) +} + +fn answer( + receipts: &Weak, + sessions: &dyn SessionTurns, + message: &StageWireMessage, +) -> ReceiptsReply { + let answered = (|| -> Result> { + let receipts = receipts + .upgrade() + .ok_or_else(|| Unavailable("this stage was unloaded".to_owned()))?; + if message.kind != WireMessageKind::Receipts { + bail!("a receipts connection carries only receipts requests"); + } + let request = + serde_json::from_slice(&message.raw_bytes).context("decode a receipts request")?; + Ok(match request { + ChainRequest::Commit(request) => { + serde_json::to_vec(&receipts.commit_session(sessions, &request)?)? + } + ChainRequest::Open(request) => serde_json::to_vec(&receipts.open_forwarded(&request)?)?, + ChainRequest::Rows(request) => serde_json::to_vec(&receipts.rows_forwarded(&request)?)?, + }) + })(); + match answered { + Ok(body) => ReceiptsReply::Answer(body), + Err(error) => refusal::reply(&error), + } +} + +#[cfg(test)] +#[path = "chain_server_tests.rs"] +mod tests; diff --git a/crates/skippy-serving/src/receipts/chain_server_tests.rs b/crates/skippy-serving/src/receipts/chain_server_tests.rs new file mode 100644 index 00000000..a2560704 --- /dev/null +++ b/crates/skippy-serving/src/receipts/chain_server_tests.rs @@ -0,0 +1,301 @@ +use std::io::Write; +use std::net::{Ipv4Addr, SocketAddr, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use skippy_protocol::binary::{ + ReceiptsReply, StageWireMessage, read_stage_message, recv_ready, recv_receipts_reply, + send_ready, write_stage_message, +}; +use skippy_receipts::binding::verify_paths; +use skippy_receipts::wire::CannotOpenReason; + +use super::{RECEIPTS_CONNECTIONS, serve_connection_until_idle}; +use crate::receipts::downstream::{ + ChainRequest, CommitRequest, Downstream, ForwardedOpen, StageConnection, +}; +use crate::receipts::kept_turns::KeptTurns; +use crate::receipts::refusal::{NotFound, Unavailable}; +use crate::receipts::reply_limits::ReplyLimits; +use crate::receipts::tests::{ + GENEROUS, POSITIONS, SESSION, cannot_open, challenge, fake_stage, record, session_turn, + sessions, stage, stage_config, turn, +}; +use crate::receipts::{StageReceipts, lock}; + +/// A stage's binary listener, as far as receipts go. +struct Served { + endpoint: String, + /// Connections accepted so far. + accepted: Arc, + /// One message per connection the stage stopped serving. + closed: mpsc::Receiver<()>, +} + +/// Serves `receipts` the way a stage's binary listener does, on an +/// ephemeral loopback port. A connection that sends nothing for `idle` is +/// closed. +fn serve_binary(receipts: Option>, idle: Duration) -> Served { + let listener = + std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).expect("bind"); + let endpoint = format!("tcp://{}", listener.local_addr().expect("address")); + let accepted = Arc::new(AtomicUsize::new(0)); + let count = accepted.clone(); + let (closing, closed) = mpsc::channel(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + count.fetch_add(1, Ordering::SeqCst); + let (receipts, closing) = (receipts.clone(), closing.clone()); + std::thread::spawn(move || { + send_ready(&mut stream).expect("ready"); + if let Ok(first) = read_stage_message(&mut stream, 0) { + let sessions = sessions(); + let _ = serve_connection_until_idle( + receipts, + sessions.as_ref(), + stream, + first, + idle, + ); + } + let _ = closing.send(()); + }); + } + }); + Served { + endpoint, + accepted, + closed, + } +} + +/// Opens a receipts connection to `endpoint` with `request`, and returns it +/// with the stage's reply. +fn connect_with(endpoint: &str, request: &ChainRequest) -> (TcpStream, ReceiptsReply) { + let address = endpoint.strip_prefix("tcp://").expect("a tcp endpoint"); + let mut stream = TcpStream::connect(address).expect("connect"); + stream.set_read_timeout(Some(GENEROUS)).expect("timeout"); + recv_ready(&mut stream).expect("ready"); + let body = serde_json::to_vec(request).expect("json"); + write_stage_message(&mut stream, &StageWireMessage::receipts(body)).expect("request"); + stream.flush().expect("flush"); + let reply = recv_receipts_reply(&mut stream, 1 << 20).expect("reply"); + (stream, reply) +} + +/// The tokens of a turn the fixture's session computes after its first: +/// its prompt holds the first turn's positions. +fn next_turn() -> crate::receipts::TurnTokens { + crate::receipts::TurnTokens { + generation_start: POSITIONS.end + 1, + sampled: 2, + ..turn() + } +} + +fn commit_request(session: &str) -> CommitRequest { + CommitRequest { + receipt_id: "r1".into(), + session: session.into(), + position_start: POSITIONS.start, + position_end: POSITIONS.end, + client_key: None, + } +} + +fn open_request(receipt_id: &str) -> ForwardedOpen { + ForwardedOpen { + challenge: challenge(receipt_id, &[3]), + turn_root: None, + } +} + +fn next_stage(endpoint: &str) -> StageConnection { + StageConnection::new(&stage_config(endpoint), GENEROUS, GENEROUS) +} + +#[test] +fn the_stage_connection_commits_and_opens_the_next_stage() { + let served = serve_binary(Some(Arc::new(stage(1, 2..4, None))), GENEROUS); + let stage0 = stage(0, 0..2, Some(Box::new(next_stage(&served.endpoint)))); + let receipt = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + let challenge = challenge("r1", &[1, 3]); + for _ in 0..2 { + let opening = stage0.open(&challenge, None).expect("opening"); + let stages: Vec = opening.stages.iter().map(|s| s.stage_index).collect(); + assert_eq!(stages, [0, 1]); + verify_paths(&receipt, &challenge, &opening).expect("paths verify"); + } + // commits have a connection of their own, and both are kept + assert_eq!(served.accepted.load(Ordering::SeqCst), 2); +} + +#[test] +fn the_stage_connection_carries_the_next_stage_error() { + let served = serve_binary(Some(Arc::new(stage(1, 2..4, None))), GENEROUS); + let next = next_stage(&served.endpoint); + let limit = ReplyLimits::commit(6); + let error = next + .commit(&commit_request("other"), limit) + .expect_err("unknown session"); + assert!( + format!("{error:#}").contains("no native sequence"), + "{error:#}" + ); + // the connection survives a refused request, and a refusal does not + // stop the next commit from being asked + next.commit(&commit_request(SESSION), limit) + .expect("commit"); + assert_eq!(served.accepted.load(Ordering::SeqCst), 1); +} + +// A receipt id the stage keeps no record of is not found on the stage +// connection either, whatever its recorder still holds, and a turn it can +// no longer open is answered as such. +#[test] +fn an_unknown_or_evicted_receipt_is_not_opened_on_the_stage_connection() { + let stage1 = Arc::new(stage(1, 2..4, None)); + let served = serve_binary(Some(stage1.clone()), GENEROUS); + let next = next_stage(&served.endpoint); + let error = next.open(&open_request("missing"), 1 << 20).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + + next.commit(&commit_request(SESSION), ReplyLimits::commit(6)) + .expect("commit"); + next.open(&open_request("r1"), 1 << 20).expect("opening"); + // the turn left the recorder's window: the stage cannot open another + // challenge of it + stage1.reports.recorder().discard("r1"); + let mut other = open_request("r1"); + other.challenge.picks[0].layer = 2; + let error = next.open(&other, 1 << 20).unwrap_err(); + let cannot = cannot_open(&error); + assert_eq!(cannot.reason, CannotOpenReason::Expired); + assert_eq!(cannot.stage_index, 1); + + // the record is dropped, as when its window has passed + *lock(&stage1.kept) = KeptTurns::default(); + let error = next.open(&open_request("r1"), 1 << 20).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); +} + +// A stage with receipts off answers a receipts message once, that it has +// none, and hangs up. The stage before then asks it no more: a next stage +// without receipts costs a turn nothing after the first. +#[test] +fn a_stage_without_receipts_refuses_receipts_messages() { + let served = serve_binary(None, GENEROUS); + let request = ChainRequest::Commit(commit_request(SESSION)); + let (_stream, reply) = connect_with(&served.endpoint, &request); + assert!(matches!(reply, ReceiptsReply::Unavailable(_)), "{reply:?}"); + served.closed.recv_timeout(GENEROUS).expect("hung up"); + + let next = next_stage(&served.endpoint); + let stage0 = stage(0, 0..2, Some(Box::new(next))); + let error = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + // the turn has no receipt, and says why + assert!(stage0.receipt("r1").expect("kept").is_err()); + let asked = served.accepted.load(Ordering::SeqCst); + record(&stage0, POSITIONS.end..POSITIONS.end + 2); + let error = stage0 + .finish_turn("r2", SESSION, session_turn(), next_turn(), None) + .unwrap_err(); + assert!(format!("{error:#}").contains("not asked"), "{error:#}"); + assert_eq!(served.accepted.load(Ordering::SeqCst), asked); +} + +// A stage that predates receipts closes the connection on the message kind +// it does not know. The turn then has no receipt, and that is all: the +// commit fails without failing anything else, and the stage is asked no +// more. +#[test] +fn a_stage_that_predates_receipts_yields_no_receipt() { + let (endpoint, accepted) = fake_stage(|_| None); + let stage0 = stage(0, 0..2, Some(Box::new(next_stage(&endpoint)))); + let error = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + let reason = stage0.receipt("r1").expect("kept").expect_err("no receipt"); + assert!(reason.contains("no receipts request"), "{reason}"); + assert!(!stage0.reports.recorder().holds_turn("r1")); + record(&stage0, POSITIONS.end..POSITIONS.end + 2); + let error = stage0 + .finish_turn("r2", SESSION, session_turn(), next_turn(), None) + .unwrap_err(); + assert!(format!("{error:#}").contains("not asked"), "{error:#}"); + assert_eq!(accepted.load(Ordering::SeqCst), 1); +} + +// A receipts connection holds a slot only while it is used: one that sends +// nothing is closed, and a stage serves only so many at once. When they are +// all held, a new connection closes the one that waited longest, so a peer +// that only holds connections cannot keep out the stage before. +#[test] +fn receipts_connections_are_counted_and_closed_when_idle() { + let stage1 = Arc::new(stage(1, 2..4, None)); + let served = serve_binary(Some(stage1.clone()), Duration::from_millis(100)); + let request = ChainRequest::Open(open_request("missing")); + let (_idle, reply) = connect_with(&served.endpoint, &request); + assert!(matches!(reply, ReceiptsReply::NotFound(_)), "{reply:?}"); + // the connection sends nothing more: the stage closes it + served + .closed + .recv_timeout(GENEROUS) + .expect("closed when idle"); + assert_eq!(stage1.connections.held(), 0); + + let served = serve_binary(Some(stage1.clone()), GENEROUS); + let mut held: Vec = (0..RECEIPTS_CONNECTIONS) + .map(|_| { + let (stream, reply) = connect_with(&served.endpoint, &request); + assert!(matches!(reply, ReceiptsReply::NotFound(_)), "{reply:?}"); + stream + }) + .collect(); + assert_eq!(stage1.connections.held(), RECEIPTS_CONNECTIONS); + let (_newest, reply) = connect_with(&served.endpoint, &request); + assert!(matches!(reply, ReceiptsReply::NotFound(_)), "{reply:?}"); + served + .closed + .recv_timeout(GENEROUS) + .expect("the oldest idle closed"); + assert_eq!(stage1.connections.held(), RECEIPTS_CONNECTIONS); + // the first connection was the one closed: the stage hung up on it + let mut oldest = held.remove(0); + let body = serde_json::to_vec(&request).expect("json"); + let _ = write_stage_message(&mut oldest, &StageWireMessage::receipts(body)); + assert!(recv_receipts_reply(&mut oldest, 1 << 20).is_err()); + // a connection that closes frees its slot + drop(held.pop()); + served.closed.recv_timeout(GENEROUS).expect("closed"); + assert_eq!(stage1.connections.held(), RECEIPTS_CONNECTIONS - 1); +} + +// A connection that lost its slot ends its wait by itself. On some +// platforms a shutdown from another thread does not end a blocked read, +// so the wait must not need one: here nothing touches the socket at all. +#[test] +fn a_connection_that_lost_its_slot_stops_waiting_without_a_shutdown() { + let listener = + std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).expect("bind"); + let _silent_peer = + TcpStream::connect(listener.local_addr().expect("address")).expect("connect"); + let (upstream, _) = listener.accept().expect("accept"); + let slots = Arc::new(super::ConnectionSlots::default()); + let slot = slots.acquire(&upstream).expect("clone").expect("a slot"); + // a newer connection took the slot + slots.lock().held.clear(); + let started = std::time::Instant::now(); + let waiting = super::wait_for_request(&upstream, &slot, GENEROUS).expect("wait"); + assert!(!waiting, "the connection ended"); + assert!(started.elapsed() < GENEROUS / 2, "{:?}", started.elapsed()); +} diff --git a/crates/skippy-serving/src/receipts/downstream.rs b/crates/skippy-serving/src/receipts/downstream.rs new file mode 100644 index 00000000..87561f32 --- /dev/null +++ b/crates/skippy-serving/src/receipts/downstream.rs @@ -0,0 +1,415 @@ +//! How a stage reaches the receipts of the stage after it: over that +//! stage's receipts HTTP API, or over the binary stage connection the +//! chain already runs on. +//! +//! On the stage connection, a stage opens dedicated connections to the +//! next stage whose messages are all [`WireMessageKind::Receipts`]. They +//! carry no activations and hold no lane, and they stay open between +//! requests. The stage that accepts one commits or opens its own part, +//! forwards the request to the stage after it the same way, and replies +//! with every later stage's part appended ([`super::chain_server`]). In a +//! Mesh split, the connections cross peers like every other stage +//! connection. +//! +//! A commit ends every turn's response, so it does not wait behind +//! another client's replay: commits have a connection of their own and a +//! short timeout, after which the turn has no receipt. A next stage that +//! issues no receipts, or that does not answer, is not asked again for a +//! while, so it costs later turns nothing. +//! +//! No reply is read past what its request can produce +//! ([`super::reply_limits`]). + +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use skippy_protocol::StageConfig; +use skippy_protocol::binary::{ + MAX_STAGE_RECEIPTS_REFUSAL_BYTES, ReceiptsReply, StageWireMessage, recv_ready, + recv_receipts_reply, write_stage_message, +}; +use skippy_receipts::attention::opening::{BlockChallenge, RowsOpening}; +use skippy_receipts::wire::{Challenge, Opening, StageCommitment}; + +use super::refusal::{self, Unavailable}; +use super::{OPENING_DIGEST_HEADER, TURN_ROOT_HEADER}; + +/// Bound on a downstream open, which may replay a whole turn. +pub(super) const OPEN_TIMEOUT: Duration = Duration::from_secs(120); +/// Bound on a downstream commit: every later stage hashes the turn's +/// leaves into a tree. Past it the turn has no receipt. +pub(super) const COMMIT_TIMEOUT: Duration = Duration::from_secs(10); +/// How long a next stage that says it issues no receipts is not asked to +/// commit. +const NO_RECEIPTS_BACKOFF: Duration = Duration::from_secs(600); +/// How long a next stage that closed the connection on a commit is not +/// asked again: one that predates receipts, or one that is restarting. +const CLOSED_BACKOFF: Duration = Duration::from_secs(60); +/// How long a next stage that did not answer a commit is not asked again. +const UNREACHABLE_BACKOFF: Duration = Duration::from_secs(30); + +/// A commit of a session's turn, as one stage asks it of the next. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) struct CommitRequest { + pub receipt_id: String, + pub session: String, + pub position_start: u32, + pub position_end: u32, + /// Hex VRF key of the client the receipt is bound to. A stage opens + /// such a turn only for a challenge with the client's proof, and pins + /// its cells for the challenge window. Absent for a turn no client can + /// challenge. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_key: Option, +} + +/// A challenge as one stage forwards it to the next. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) struct ForwardedOpen { + pub challenge: Challenge, + /// Hex turn root of a bound receipt, which the challenge's proof is + /// over. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turn_root: Option, +} + +/// A block challenge as one stage forwards it to the next. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) struct ForwardedRows { + pub blocks: BlockChallenge, + /// Hex digest of the opening stage 0 signed for a bound receipt, which + /// the rows' proof is over. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opening: Option, +} + +/// The body of a receipts request on the stage connection. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum ChainRequest { + Commit(CommitRequest), + Open(ForwardedOpen), + Rows(ForwardedRows), +} + +/// The receipts of the stages after this one. Each answer may hold at most +/// `limit` bytes. +pub(super) trait Downstream: Send + Sync { + fn commit(&self, request: &CommitRequest, limit: usize) -> Result>; + fn open(&self, request: &ForwardedOpen, limit: usize) -> Result; + fn rows(&self, request: &ForwardedRows, limit: usize) -> Result; +} + +/// Why an exchange with the next stage gave no reply. +#[derive(Debug)] +enum Failure { + /// The next stage did not answer in time, or could not be reached. + Unreachable(anyhow::Error), + /// The next stage closed the connection on the request: it does not + /// serve receipts, as a stage that predates them. + NoReceipts(anyhow::Error), + /// The next stage sent what this stage does not take for a reply: one + /// longer than the request can produce, or no receipts reply at all. + Invalid(anyhow::Error), +} + +impl Failure { + fn of(error: std::io::Error) -> Self { + use std::io::ErrorKind::{InvalidData, TimedOut, WouldBlock}; + match error.kind() { + TimedOut | WouldBlock => Self::Unreachable( + anyhow::Error::new(error).context("the next stage did not answer"), + ), + InvalidData => { + Self::Invalid(anyhow::Error::new(error).context("the next stage's reply")) + } + _ => Self::NoReceipts( + anyhow::Error::new(error).context("the next stage answered no receipts request"), + ), + } + } + + fn into_error(self) -> anyhow::Error { + match self { + Self::Unreachable(error) | Self::Invalid(error) => error, + Self::NoReceipts(error) => anyhow::Error::new(Unavailable(format!("{error:#}"))), + } + } +} + +/// When the next stage is asked to commit again, and why not before. +#[derive(Default)] +struct CommitBackoff(Mutex>); + +impl CommitBackoff { + fn lock(&self) -> std::sync::MutexGuard<'_, Option<(Instant, String)>> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Fails at once while the next stage is not to be asked. + fn check(&self, now: Instant) -> Result<()> { + let mut state = self.lock(); + match &*state { + Some((until, why)) if now < *until => bail!("the next stage is not asked: {why}"), + _ => { + *state = None; + Ok(()) + } + } + } + + /// Notes what a commit came to: `wait` is how long its reply says not + /// to ask again ([`commit_backoff`]), and `result` why. + fn note(&self, wait: Option, result: &Result, now: Instant) { + if let (Some(wait), Err(error)) = (wait, result) { + *self.lock() = Some((now + wait, format!("{error:#}"))); + } + } +} + +/// How long the next stage is not asked to commit after it answered a +/// commit with `reply`; `None` when it answered or refused the commit +/// itself, which says nothing about the next one. +fn commit_backoff(reply: &Result) -> Option { + match reply { + Ok(ReceiptsReply::Unavailable(_)) => Some(NO_RECEIPTS_BACKOFF), + Err(Failure::NoReceipts(_)) => Some(CLOSED_BACKOFF), + Err(Failure::Unreachable(_)) => Some(UNREACHABLE_BACKOFF), + _ => None, + } +} + +/// The next stage's receipts HTTP API. +pub(super) struct HttpDownstream { + url: String, + client: reqwest::blocking::Client, + commit_timeout: Duration, + open_timeout: Duration, + backoff: CommitBackoff, +} + +impl HttpDownstream { + pub(super) fn new(url: &str, commit_timeout: Duration, open_timeout: Duration) -> Result { + Ok(Self { + url: url.trim_end_matches('/').to_owned(), + client: reqwest::blocking::Client::builder() + .build() + .context("build receipts HTTP client")?, + commit_timeout, + open_timeout, + backoff: CommitBackoff::default(), + }) + } + + /// Posts `body` and reads the reply, an answer of at most `limit` bytes. + fn post( + &self, + route: &str, + body: &impl Serialize, + header: Option<(&str, &str)>, + timeout: Duration, + limit: usize, + ) -> Result { + let mut request = self + .client + .post(format!("{}/receipts/{route}", self.url)) + .timeout(timeout) + .json(body); + if let Some((name, value)) = header { + request = request.header(name, value); + } + let response = request.send().map_err(|error| { + Failure::Unreachable(anyhow::Error::new(error).context("the next stage's receipts API")) + })?; + let status = response.status(); + let limit = if status.is_success() { + limit + } else { + MAX_STAGE_RECEIPTS_REFUSAL_BYTES + }; + let mut bytes = Vec::new(); + response + .take(limit as u64 + 1) + .read_to_end(&mut bytes) + .map_err(Failure::of)?; + if bytes.len() > limit { + return Err(Failure::Invalid(anyhow::anyhow!( + "the next stage's reply exceeds what its request can produce" + ))); + } + Ok(http_reply(status, bytes)) + } +} + +/// The reply an HTTP status and body of the receipts API stand for. +fn http_reply(status: reqwest::StatusCode, body: Vec) -> ReceiptsReply { + use reqwest::StatusCode; + if status.is_success() { + return ReceiptsReply::Answer(body); + } + let json: Option = serde_json::from_slice(&body).ok(); + let field = |name: &str| json.as_ref().and_then(|json| json.get(name)).cloned(); + let reason = field("error") + .and_then(|error| error.as_str().map(str::to_owned)) + .unwrap_or_else(|| String::from_utf8_lossy(&body).into_owned()); + let reason = format!("{status}: {reason}"); + match status { + StatusCode::NOT_FOUND => ReceiptsReply::NotFound(reason), + StatusCode::SERVICE_UNAVAILABLE => ReceiptsReply::Unavailable(reason), + StatusCode::CONFLICT | StatusCode::GONE => field("cannot_open") + .and_then(|cannot| serde_json::to_vec(&cannot).ok()) + .map_or(ReceiptsReply::Refused(reason), ReceiptsReply::CannotOpen), + _ => ReceiptsReply::Refused(reason), + } +} + +/// The typed answer of a reply, or why there is none. +fn decode(reply: Result) -> Result { + let bytes = refusal::answer(reply.map_err(Failure::into_error)?)?; + serde_json::from_slice(&bytes).context("decode the next stage's receipts") +} + +impl Downstream for HttpDownstream { + fn commit(&self, request: &CommitRequest, limit: usize) -> Result> { + self.backoff.check(Instant::now())?; + let reply = self.post("commit", request, None, self.commit_timeout, limit); + let wait = commit_backoff(&reply); + let result = decode(reply); + self.backoff.note(wait, &result, Instant::now()); + result + } + + fn open(&self, request: &ForwardedOpen, limit: usize) -> Result { + let root = request + .turn_root + .as_deref() + .map(|root| (TURN_ROOT_HEADER, root)); + decode(self.post("open", &request.challenge, root, self.open_timeout, limit)) + } + + fn rows(&self, request: &ForwardedRows, limit: usize) -> Result { + let opening = request + .opening + .as_deref() + .map(|digest| (OPENING_DIGEST_HEADER, digest)); + decode(self.post("rows", &request.blocks, opening, self.open_timeout, limit)) + } +} + +/// One kept connection to the next stage; one request runs on it at a time. +struct Lane { + timeout: Duration, + stream: Mutex>, +} + +impl Lane { + fn new(timeout: Duration) -> Self { + Self { + timeout, + stream: Mutex::new(None), + } + } +} + +/// The next stage over receipts connections of the binary stage protocol: +/// one for commits and one for openings and rows. +pub(super) struct StageConnection { + config: StageConfig, + commits: Lane, + openings: Lane, + backoff: CommitBackoff, +} + +impl StageConnection { + pub(super) fn new( + config: &StageConfig, + commit_timeout: Duration, + open_timeout: Duration, + ) -> Self { + Self { + config: config.clone(), + commits: Lane::new(commit_timeout), + openings: Lane::new(open_timeout), + backoff: CommitBackoff::default(), + } + } + + fn connect(&self, timeout: Duration) -> Result { + let connect = || -> Result { + let mut stream = + crate::binary_transport::connect_binary_downstream(&self.config, timeout)? + .context("this stage has no stage after it")?; + crate::binary_transport::send_client_ready_hello_if_enabled(&mut stream)?; + stream.set_read_timeout(Some(timeout))?; + stream.set_write_timeout(Some(timeout))?; + recv_ready(&mut stream).context("the next stage did not get ready")?; + Ok(stream) + }; + connect().map_err(Failure::Unreachable) + } + + fn request( + &self, + lane: &Lane, + request: &ChainRequest, + limit: usize, + ) -> Result { + let body = serde_json::to_vec(request) + .map_err(|error| Failure::Unreachable(anyhow::Error::new(error)))?; + let mut kept = lane.stream.lock().unwrap_or_else(PoisonError::into_inner); + let (mut stream, reused) = match kept.take() { + Some(stream) => (stream, true), + None => (self.connect(lane.timeout)?, false), + }; + let reply = match exchange(&mut stream, &body, limit) { + // a kept connection the next stage closed since its last + // request: once more, on a new one. A request that timed out is + // not sent again. + Err(Failure::NoReceipts(_)) if reused => { + stream = self.connect(lane.timeout)?; + exchange(&mut stream, &body, limit)? + } + reply => reply?, + }; + *kept = Some(stream); + Ok(reply) + } +} + +fn exchange(stream: &mut TcpStream, body: &[u8], limit: usize) -> Result { + write_stage_message(&mut *stream, &StageWireMessage::receipts(body.to_vec())) + .and_then(|()| stream.flush()) + .map_err(Failure::of)?; + recv_receipts_reply(&mut *stream, limit).map_err(Failure::of) +} + +impl Downstream for StageConnection { + fn commit(&self, request: &CommitRequest, limit: usize) -> Result> { + self.backoff.check(Instant::now())?; + let request = ChainRequest::Commit(request.clone()); + let reply = self.request(&self.commits, &request, limit); + let wait = commit_backoff(&reply); + let result = decode(reply); + self.backoff.note(wait, &result, Instant::now()); + result + } + + fn open(&self, request: &ForwardedOpen, limit: usize) -> Result { + let request = ChainRequest::Open(request.clone()); + decode(self.request(&self.openings, &request, limit)) + } + + fn rows(&self, request: &ForwardedRows, limit: usize) -> Result { + let request = ChainRequest::Rows(request.clone()); + decode(self.request(&self.openings, &request, limit)) + } +} + +#[cfg(test)] +#[path = "downstream_tests.rs"] +mod tests; diff --git a/crates/skippy-serving/src/receipts/downstream_tests.rs b/crates/skippy-serving/src/receipts/downstream_tests.rs new file mode 100644 index 00000000..96eb3970 --- /dev/null +++ b/crates/skippy-serving/src/receipts/downstream_tests.rs @@ -0,0 +1,190 @@ +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Duration; + +use reqwest::StatusCode; +use skippy_protocol::binary::ReceiptsReply; +use skippy_receipts::wire::{CannotOpen, CannotOpenReason, StageCommitment}; + +use super::{ChainRequest, CommitRequest, Downstream, ForwardedOpen, StageConnection, http_reply}; +use crate::receipts::refusal::{self, NotFound, Unavailable}; +use crate::receipts::reply_limits::ReplyLimits; +use crate::receipts::tests::{ + GENEROUS, POSITIONS, SESSION, challenge, fake_stage, session_turn, sessions, stage, + stage_config, turn, +}; + +fn commit_request() -> CommitRequest { + CommitRequest { + receipt_id: "r1".into(), + session: SESSION.into(), + position_start: POSITIONS.start, + position_end: POSITIONS.end, + client_key: None, + } +} + +/// What an honest stage 1 commits for the fixture's turn. +fn honest_commitments() -> Vec { + stage(1, 2..4, None) + .commit_session(sessions().as_ref(), &commit_request()) + .expect("commit") +} + +fn answer(value: &impl serde::Serialize) -> Option { + Some(ReceiptsReply::Answer(serde_json::to_vec(value).unwrap())) +} + +// Stage 0 signs what the later stages commit, so it keeps a commitment +// only when it continues the plan: the next stage, the next layers, the +// leaves of the turn's positions. +#[test] +fn a_later_stages_commitment_must_continue_the_plan() { + type Change = fn(&mut StageCommitment); + let forgeries: [Change; 4] = [ + |commitment| commitment.stage_index = 5, + |commitment| commitment.layer_start = 0, + |commitment| commitment.leaf_count *= 2, + |commitment| commitment.root = "not a root".into(), + ]; + for (i, forge) in forgeries.into_iter().enumerate() { + let mut forged = honest_commitments(); + forge(&mut forged[0]); + let (endpoint, _) = fake_stage(move |_| answer(&forged)); + let next = StageConnection::new(&stage_config(&endpoint), GENEROUS, GENEROUS); + let stage0 = stage(0, 0..2, Some(Box::new(next))); + let result = stage0.finish_turn("r1", SESSION, session_turn(), turn(), None); + assert!(result.is_err(), "forgery {i} was signed"); + assert!(!stage0.reports.recorder().holds_turn("r1")); + } + let honest = honest_commitments(); + let (endpoint, _) = fake_stage(move |_| answer(&honest)); + let next = StageConnection::new(&stage_config(&endpoint), GENEROUS, GENEROUS); + let stage0 = stage(0, 0..2, Some(Box::new(next))); + let receipt = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + assert_eq!(receipt.stages.len(), 2); +} + +// A stage reads no more of a later stage's reply than its request can +// produce: a commit's few commitments, an opening's picked leaves. +#[test] +fn a_reply_longer_than_its_request_can_produce_is_refused() { + let honest = honest_commitments(); + let (endpoint, _) = fake_stage(move |request| match request { + ChainRequest::Commit(request) if request.receipt_id == "padded" => { + Some(ReceiptsReply::Answer(vec![b' '; 4 << 20])) + } + ChainRequest::Commit(_) => answer(&honest), + _ => Some(ReceiptsReply::Answer(vec![b' '; 64 << 20])), + }); + let config = stage_config(&endpoint); + let padded = StageConnection::new(&config, GENEROUS, GENEROUS); + let stage0 = stage(0, 0..2, Some(Box::new(padded))); + let error = stage0 + .finish_turn("padded", SESSION, session_turn(), turn(), None) + .unwrap_err(); + assert!(format!("{error:#}").contains("exceeds"), "{error:#}"); + + let next = StageConnection::new(&config, GENEROUS, GENEROUS); + let stage0 = stage(0, 0..2, Some(Box::new(next))); + stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + // the challenge picks nothing on the later stage: boundary leaves only + let error = stage0.open(&challenge("r1", &[1]), None).unwrap_err(); + assert!(format!("{error:#}").contains("exceeds"), "{error:#}"); +} + +// A commit ends every turn's response, so it has a connection of its own: +// it does not wait for an opening that replays another client's turn. +#[test] +fn a_commit_does_not_wait_behind_an_opening() { + let (opening, opened) = mpsc::channel(); + let (finish, finished) = mpsc::channel::<()>(); + let (opening, finished) = (Mutex::new(opening), Mutex::new(finished)); + let (endpoint, accepted) = fake_stage(move |request| match request { + ChainRequest::Commit(_) => Some(ReceiptsReply::Refused("committed".into())), + _ => { + // an opening that replays for as long as the test wants + opening.lock().unwrap().send(()).unwrap(); + let _ = finished.lock().unwrap().recv_timeout(GENEROUS); + Some(ReceiptsReply::Refused("opened".into())) + } + }); + let next = Arc::new(StageConnection::new( + &stage_config(&endpoint), + GENEROUS, + GENEROUS, + )); + let opener = next.clone(); + let open = std::thread::spawn(move || { + let request = ForwardedOpen { + challenge: challenge("r1", &[3]), + turn_root: None, + }; + opener.open(&request, 1 << 20) + }); + opened.recv_timeout(GENEROUS).expect("the opening started"); + let error = next + .commit(&commit_request(), ReplyLimits::commit(6)) + .unwrap_err(); + assert!(format!("{error:#}").contains("committed"), "{error:#}"); + finish.send(()).unwrap(); + let error = open.join().unwrap().unwrap_err(); + assert!(format!("{error:#}").contains("opened"), "{error:#}"); + assert_eq!(accepted.load(Ordering::SeqCst), 2); +} + +// A next stage that does not answer a commit costs one short wait: the turn +// has no receipt, and the stage is not asked again for a while. +#[test] +fn a_next_stage_that_does_not_answer_is_not_asked_again() { + let (release, released) = mpsc::channel::<()>(); + let released = Mutex::new(released); + let (endpoint, accepted) = fake_stage(move |_| { + // holds the request until the test ends + let _ = released.lock().unwrap().recv_timeout(GENEROUS); + None + }); + let short = Duration::from_millis(200); + let next = StageConnection::new(&stage_config(&endpoint), short, GENEROUS); + let limit = ReplyLimits::commit(6); + let error = next.commit(&commit_request(), limit).unwrap_err(); + assert!(format!("{error:#}").contains("did not answer"), "{error:#}"); + let error = next.commit(&commit_request(), limit).unwrap_err(); + assert!(format!("{error:#}").contains("not asked"), "{error:#}"); + assert_eq!(accepted.load(Ordering::SeqCst), 1); + drop(release); +} + +// The receipts API of a next stage says by its status what the stage +// connection says by its reply kind. +#[test] +fn an_http_status_stands_for_a_reply_kind() { + let cannot = CannotOpen { + receipt_id: "r".into(), + stage_index: 1, + reason: CannotOpenReason::Expired, + detail: "gone".into(), + }; + let body = |value: serde_json::Value| serde_json::to_vec(&value).unwrap(); + let error = |status, json| refusal::answer(http_reply(status, body(json))).unwrap_err(); + let gone = serde_json::json!({ "error": "gone", "cannot_open": cannot }); + let answered = error(StatusCode::GONE, gone.clone()); + assert_eq!(answered.downcast_ref::(), Some(&cannot)); + let answered = error(StatusCode::CONFLICT, gone); + assert_eq!(answered.downcast_ref::(), Some(&cannot)); + let missing = serde_json::json!({ "error": "no receipt r" }); + let answered = error(StatusCode::NOT_FOUND, missing.clone()); + assert!(answered.downcast_ref::().is_some()); + let answered = error(StatusCode::SERVICE_UNAVAILABLE, missing.clone()); + assert!(answered.downcast_ref::().is_some()); + let answered = error(StatusCode::BAD_REQUEST, missing); + assert!(format!("{answered:#}").contains("no receipt r")); + assert_eq!( + refusal::answer(http_reply(StatusCode::OK, b"[]".to_vec())).unwrap(), + b"[]" + ); +} diff --git a/crates/skippy-serving/src/receipts/http_api.rs b/crates/skippy-serving/src/receipts/http_api.rs new file mode 100644 index 00000000..23e0667f --- /dev/null +++ b/crates/skippy-serving/src/receipts/http_api.rs @@ -0,0 +1,443 @@ +//! The receipts HTTP routes: a stage's own API on its receipts address, and +//! the routes a node serves on its OpenAI surface for clients that reach it +//! only there. +//! +//! Every answer that is not an opening says which kind it is by its status: +//! +//! - 404: the stage keeps no record of the receipt id; +//! - 403: the route opens only bound receipts, and this one is not bound; +//! - 409 or 410: the request is one the stage would answer, but it can no +//! longer open the turn ([`CannotOpen`]); 410 when the turn left the +//! opening window, 409 when a later request overwrote its cells or the +//! stage lost track of them. The body holds `cannot_open` with the reason +//! and the stage, and for a bound receipt the node signs it; +//! - 503: the stage was unloaded, or it is busy with other openings +//! ([`super::opening_queue`]); a busy stage names when to try again in +//! `Retry-After` and in the body's `retry_after_secs`; +//! - 400: anything else, a refused or malformed request among them. +//! +//! The routes hold the stage only weakly, so a host that keeps a router +//! after it unloads the model keeps neither the model nor the receipts. + +use std::sync::{Arc, Mutex, Weak}; +use std::thread::JoinHandle; + +use anyhow::{Context, Result, anyhow}; +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::commitment::{Hash, hex_array}; +use skippy_receipts::turn; +use skippy_receipts::wire::{CannotOpen, CannotOpenReason, Challenge, Receipt, StageCommitment}; + +use super::downstream::CommitRequest; +use super::opening_queue::Busy; +use super::refusal::{NotFound, Unavailable}; +use super::{OPENING_DIGEST_HEADER, SessionTurns, StageReceipts, TURN_ROOT_HEADER}; +use crate::runtime_state::RuntimeState; + +/// What the routes reach: the stage's receipts and its sessions, while the +/// stage is loaded. +#[derive(Clone)] +pub(super) struct ApiState { + pub receipts: Weak, + pub sessions: Weak, +} + +impl ApiState { + pub(super) fn of(receipts: &Arc, runtime: &Arc>) -> Self { + let sessions: Weak> = Arc::downgrade(runtime); + Self { + receipts: Arc::downgrade(receipts), + sessions, + } + } + + fn receipts(&self) -> Result> { + self.receipts + .upgrade() + .ok_or_else(|| anyhow::Error::new(Unavailable("this stage was unloaded".to_owned()))) + } +} + +/// The receipts API thread of a stage; it stops serving when this is +/// dropped. +pub(super) struct ApiHandle { + stop: Option>, + thread: Option>, +} + +impl ApiHandle { + /// The API thread, for a test to wait for its end. + #[cfg(test)] + pub(super) fn take_thread(&mut self) -> JoinHandle<()> { + self.thread.take().expect("the receipts API thread") + } +} + +impl Drop for ApiHandle { + /// Tells the thread to stop. It is not waited for: a request it still + /// answers may be what drops the stage. + fn drop(&mut self) { + self.stop.take(); + self.thread.take(); + } +} + +pub(super) fn spawn_api(listener: std::net::TcpListener, router: Router) -> Result { + listener.set_nonblocking(true)?; + let (stop, stopped) = tokio::sync::oneshot::channel(); + let thread = std::thread::Builder::new() + .name("skippy-receipts-api".into()) + .spawn(move || serve(listener, router, stopped)) + .context("spawn receipts API thread")?; + Ok(ApiHandle { + stop: Some(stop), + thread: Some(thread), + }) +} + +fn serve( + listener: std::net::TcpListener, + router: Router, + stopped: tokio::sync::oneshot::Receiver<()>, +) { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + tracing::error!("receipts API runtime: {error}"); + return; + } + }; + runtime.block_on(async move { + let listener = match tokio::net::TcpListener::from_std(listener) { + Ok(listener) => listener, + Err(error) => { + tracing::error!("receipts API listener: {error}"); + return; + } + }; + // the sender is dropped, never used: either way the stage is gone + let stopped = async move { + let _ = stopped.await; + }; + if let Err(error) = axum::serve(listener, router) + .with_graceful_shutdown(stopped) + .await + { + tracing::error!("receipts API stopped: {error}"); + } + }); +} + +/// A stage's own receipts API. +pub(super) fn router(state: ApiState) -> Router { + Router::new() + .route("/receipts/commit", post(commit_handler)) + .route("/receipts/open", post(open_handler)) + .route("/receipts/rows", post(rows_handler)) + .route("/receipts/{id}", get(receipt_handler)) + .with_state(state) +} + +/// The routes of the OpenAI surface: `POST /v1/receipts/open` and +/// `POST /v1/receipts/rows`, for bound receipts only. +pub(super) fn client_routes(state: ApiState) -> Router { + Router::new() + .route("/v1/receipts/open", post(bound_open_handler)) + .route("/v1/receipts/rows", post(bound_rows_handler)) + .with_state(state) +} + +/// An answer that is not the one asked for: its status, its JSON body, and +/// the node's signature of the body when it signs one. +struct ApiError { + status: StatusCode, + body: serde_json::Value, + cannot_open: Option, + /// Seconds after which a busy stage takes the request again. + retry_after: Option, +} + +impl ApiError { + fn new(status: StatusCode, error: &anyhow::Error) -> Self { + Self { + status, + body: serde_json::json!({ "error": format!("{error:#}") }), + cannot_open: None, + retry_after: None, + } + } +} + +impl From for ApiError { + fn from(error: anyhow::Error) -> Self { + if let Some(busy) = error.downcast_ref::() { + let seconds = busy.retry_after.as_secs(); + return Self { + status: StatusCode::SERVICE_UNAVAILABLE, + body: serde_json::json!({ "error": busy.to_string(), "retry_after_secs": seconds }), + cannot_open: None, + retry_after: Some(seconds), + }; + } + if let Some(cannot) = error.downcast_ref::() { + let status = match cannot.reason { + CannotOpenReason::Expired => StatusCode::GONE, + _ => StatusCode::CONFLICT, + }; + return Self { + status, + body: serde_json::json!({ "error": cannot.to_string(), "cannot_open": cannot }), + cannot_open: Some(cannot.clone()), + retry_after: None, + }; + } + let status = if error.downcast_ref::().is_some() { + StatusCode::NOT_FOUND + } else if error.downcast_ref::().is_some() { + StatusCode::SERVICE_UNAVAILABLE + } else { + StatusCode::BAD_REQUEST + }; + Self::new(status, &error) + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let mut response = (self.status, Json(self.body)).into_response(); + with_retry_after(&mut response, self.retry_after); + response + } +} + +fn with_retry_after(response: &mut Response, seconds: Option) { + if let Some(seconds) = seconds { + response + .headers_mut() + .insert(axum::http::header::RETRY_AFTER, seconds.into()); + } +} + +async fn blocking( + work: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(work) + .await + .map_err(|error| ApiError::from(anyhow!("receipts worker failed: {error}")))? + .map_err(ApiError::from) +} + +/// The hash a stage before this one sent along in `header`, if any. +fn forwarded_hash(headers: &HeaderMap, header: &str) -> Result, ApiError> { + headers + .get(header) + .map(|value| { + let text = value.to_str().context("a forwarded hash is hex")?; + hex_array(text, "a forwarded hash") + }) + .transpose() + .map_err(ApiError::from) +} + +async fn commit_handler( + State(state): State, + Json(request): Json, +) -> Result>, ApiError> { + blocking(move || { + let receipts = state.receipts()?; + let sessions = state + .sessions + .upgrade() + .ok_or_else(|| anyhow::Error::new(Unavailable("this stage was unloaded".into())))?; + receipts.commit_session(sessions.as_ref(), &request) + }) + .await + .map(Json) +} + +/// Answers with the opening's bytes and, for a bound receipt, the node's +/// signature of exactly those bytes. +async fn open_handler( + State(state): State, + headers: HeaderMap, + Json(challenge): Json, +) -> Result { + let root = forwarded_hash(&headers, TURN_ROOT_HEADER)?; + opening_response(state, challenge, root).await +} + +/// Refuses a receipt the client routes do not open: one that is not bound. +fn bound_only(state: &ApiState, id: &str) -> Result<(), ApiError> { + match state.receipts().and_then(|receipts| receipts.is_bound(id)) { + Ok(true) => Ok(()), + Ok(false) => Err(ApiError::new( + StatusCode::FORBIDDEN, + &anyhow!("receipt {id} is not bound to a client key"), + )), + Err(error) => Err(ApiError::from(error)), + } +} + +/// [`open_handler`] for a bound receipt only. The body may also name the +/// `model`, which a Mesh node routes the request by. +async fn bound_open_handler( + State(state): State, + Json(challenge): Json, +) -> Result { + bound_only(&state, &challenge.receipt_id)?; + opening_response(state, challenge, None).await +} + +/// The JSON `answer` with the node's signature, or the error of a turn the +/// node cannot open, signed likewise when the receipt is one it signs for. +fn signed_answer( + receipts: &StageReceipts, + receipt_id: &str, + request: &Hash, + answer: Result<(Vec, Option)>, +) -> Result { + match answer { + Ok((bytes, signature)) => Ok(Signed { + status: StatusCode::OK, + bytes, + signature, + retry_after: None, + }), + Err(error) => { + let refused = ApiError::from(error); + let bytes = serde_json::to_vec(&refused.body)?; + let signature = refused + .cannot_open + .and_then(|_| receipts.sign_cannot_open(receipt_id, request, &bytes)); + Ok(Signed { + status: refused.status, + bytes, + signature, + retry_after: refused.retry_after, + }) + } + } +} + +/// An answer's status and JSON body, with the node's signature of the body +/// when it signs one. +struct Signed { + status: StatusCode, + bytes: Vec, + signature: Option, + retry_after: Option, +} + +async fn opening_response( + state: ApiState, + challenge: Challenge, + forwarded_root: Option, +) -> Result { + let signed = blocking(move || { + let receipts = state.receipts()?; + let opened = receipts + .open(&challenge, forwarded_root) + .and_then(|opening| { + let bytes = serde_json::to_vec(&opening)?; + let signature = receipts.sign_opening(&challenge, &bytes)?; + Ok((bytes, signature)) + }); + signed_answer( + &receipts, + &challenge.receipt_id, + &challenge.digest(), + opened, + ) + }) + .await?; + signed_response(signed) +} + +/// A JSON body with the node's signature of it, when it signed it. +fn signed_response(signed: Signed) -> Result { + let mut response = ( + signed.status, + [(axum::http::header::CONTENT_TYPE, "application/json")], + signed.bytes, + ) + .into_response(); + with_retry_after(&mut response, signed.retry_after); + if let Some(signature) = signed.signature { + response.headers_mut().insert( + turn::OPENING_SIGNATURE_HEADER, + signature + .parse() + .context("a hex signature is a header value")?, + ); + } + Ok(response) +} + +/// Answers with the rows' bytes and, for a bound receipt, the node's +/// signature of exactly those bytes. +async fn rows_handler( + State(state): State, + headers: HeaderMap, + Json(challenge): Json, +) -> Result { + let opening = forwarded_hash(&headers, OPENING_DIGEST_HEADER)?; + rows_response(state, challenge, opening).await +} + +/// [`rows_handler`] for a bound receipt that was challenged. +async fn bound_rows_handler( + State(state): State, + Json(challenge): Json, +) -> Result { + bound_only(&state, &challenge.receipt_id)?; + rows_response(state, challenge, None).await +} + +async fn rows_response( + state: ApiState, + blocks: BlockChallenge, + forwarded_opening: Option, +) -> Result { + let signed = blocking(move || { + let receipts = state.receipts()?; + let opened = receipts.rows(&blocks, forwarded_opening).and_then(|rows| { + let bytes = serde_json::to_vec(&rows)?; + let signature = receipts.sign_rows(&blocks, &bytes)?; + Ok((bytes, signature)) + }); + signed_answer(&receipts, &blocks.receipt_id, &blocks.digest(), opened) + }) + .await?; + signed_response(signed) +} + +async fn receipt_handler( + State(state): State, + Path(id): Path, +) -> Result, ApiError> { + // stage 0 commits a turn as its response ends, so a client may ask + // before the receipt exists + match state.receipts()?.receipt(&id) { + Some(Ok(receipt)) => Ok(Json(Receipt::clone(&receipt))), + Some(Err(reason)) => Err(ApiError::new( + StatusCode::BAD_REQUEST, + &anyhow!("turn {id} got no receipt: {reason}"), + )), + None => Err(ApiError::new( + StatusCode::NOT_FOUND, + &anyhow!("no receipt {id}"), + )), + } +} + +#[cfg(test)] +#[path = "http_api_tests.rs"] +mod tests; diff --git a/crates/skippy-serving/src/receipts/http_api_tests.rs b/crates/skippy-serving/src/receipts/http_api_tests.rs new file mode 100644 index 00000000..738f0356 --- /dev/null +++ b/crates/skippy-serving/src/receipts/http_api_tests.rs @@ -0,0 +1,243 @@ +use std::sync::Arc; + +use reqwest::StatusCode; +use reqwest::blocking::{Client, Response}; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::recorder::MemoryOp; +use skippy_receipts::turn; +use skippy_receipts::wire::{CannotOpen, CannotOpenReason, Challenge, Receipt}; + +use super::{client_routes, router}; +use crate::receipts::downstream::CommitRequest; +use crate::receipts::kept_turns::KeptTurns; +use crate::receipts::tests::{ + POSITIONS, SEQ, SESSION, api_state, bound_turn, chain, challenge, serve_routes, session_turn, + stage, turn as turn_tokens, +}; +use crate::receipts::{StageReceipts, lock}; + +fn post(url: &str, route: &str, body: &impl serde::Serialize) -> Response { + Client::new() + .post(format!("{url}{route}")) + .json(body) + .send() + .expect("reply") +} + +/// A single stage that issued the bound receipt `r1`, served on its own +/// API and on the client routes, with the challenge its client draws. +fn served_bound_turn() -> (Arc, String, Receipt, Challenge) { + let receipts = Arc::new(stage(0, 0..4, None)); + let (receipt, challenge) = bound_turn(&receipts, "r1", &[1]); + let routes = router(api_state(&receipts)).merge(client_routes(api_state(&receipts))); + (receipts.clone(), serve_routes(routes), receipt, challenge) +} + +#[test] +fn downstream_rejects_an_unknown_session() { + let downstream = chain().downstream; + let reply = post( + &downstream, + "/receipts/commit", + &CommitRequest { + receipt_id: "r1".into(), + session: "other".into(), + position_start: POSITIONS.start, + position_end: POSITIONS.end, + client_key: None, + }, + ); + assert_eq!(reply.status(), StatusCode::BAD_REQUEST); + assert!(reply.text().expect("body").contains("no native sequence")); +} + +// The OpenAI surface opens only a bound receipt, for its client's challenge. +#[test] +fn the_client_route_opens_only_bound_receipts() { + let unbound = Arc::new(stage(0, 0..4, None)); + unbound + .finish_turn("unbound", SESSION, session_turn(), turn_tokens(), None) + .expect("receipt"); + let unbound_url = serve_routes(client_routes(api_state(&unbound))); + let (_receipts, url, receipt, bound) = served_bound_turn(); + let open_at = |url: &str, challenge: &Challenge| { + let mut body = serde_json::to_value(challenge).unwrap(); + body["model"] = "model".into(); + post(url, "/v1/receipts/open", &body) + }; + + let reply = open_at(&unbound_url, &challenge("unbound", &[1])); + assert_eq!(reply.status(), StatusCode::FORBIDDEN); + assert_eq!( + open_at(&url, &challenge("missing", &[1])).status(), + StatusCode::NOT_FOUND + ); + + let mut unproven = bound.clone(); + unproven.proof = None; + assert_eq!(open_at(&url, &unproven).status(), StatusCode::BAD_REQUEST); + let reply = open_at(&url, &bound); + assert!(reply.status().is_success(), "{}", reply.status()); + let signature = reply + .headers() + .get(turn::OPENING_SIGNATURE_HEADER) + .expect("signed") + .to_str() + .unwrap() + .to_owned(); + let bytes = reply.bytes().expect("body"); + let verified = turn::verify(&receipt, None).unwrap(); + turn::verify_opening(&verified, &bound, &bytes, &signature).expect("signature"); +} + +// A stage busy with other openings answers 503 with a time to try again, +// and does not admit the challenge: the client's retry is opened. +#[test] +fn a_busy_stage_names_a_retry_time_and_keeps_the_challenge_open() { + use crate::receipts::opening_queue::{MAX_WAITING, RETRY_AFTER}; + let (receipts, url, _, challenge) = served_bound_turn(); + let running = receipts.queue.enter(None).unwrap(); + let waiters: Vec<_> = (0..MAX_WAITING) + .map(|i| { + let receipts = receipts.clone(); + std::thread::spawn(move || { + let key = Some([u8::try_from(i).unwrap() + 10; 32]); + drop(receipts.queue.enter(key)); + }) + }) + .collect(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while receipts.queue.waiting() < MAX_WAITING { + assert!(std::time::Instant::now() < deadline, "the waiters queue"); + std::thread::yield_now(); + } + let reply = post(&url, "/v1/receipts/open", &challenge); + assert_eq!(reply.status(), StatusCode::SERVICE_UNAVAILABLE); + let retry = reply.headers().get("retry-after").expect("a retry time"); + assert_eq!(retry.to_str().unwrap(), RETRY_AFTER.as_secs().to_string()); + drop(running); + for waiter in waiters { + waiter.join().unwrap(); + } + let reply = post(&url, "/v1/receipts/open", &challenge); + assert!(reply.status().is_success(), "{}", reply.status()); +} + +// The receipt route needs only the id, so it shows nobody a bound turn's +// tokens; an unbound receipt is shown whole, as before. +#[test] +fn the_receipt_route_shows_no_tokens_of_a_bound_turn() { + let (_receipts, url, receipt, _) = served_bound_turn(); + assert!(!receipt.tokens.is_empty()); + let fetched: Receipt = reqwest::blocking::get(format!("{url}/receipts/r1")) + .expect("reply") + .json() + .expect("a receipt"); + assert!(fetched.tokens.is_empty() && fetched.final_token.is_none()); + assert_eq!(fetched.stages, receipt.stages); + + let receipts = Arc::new(stage(0, 0..4, None)); + let unbound = receipts + .finish_turn("unbound", SESSION, session_turn(), turn_tokens(), None) + .expect("receipt"); + let url = serve_routes(router(api_state(&receipts))); + let fetched: Receipt = reqwest::blocking::get(format!("{url}/receipts/unbound")) + .expect("reply") + .json() + .expect("a receipt"); + assert_eq!(fetched.tokens, unbound.tokens); +} + +// A receipt id the stage keeps no record of is not found on every route, +// whatever the recorder still holds: nothing opens it without the proof +// its record asked for. +#[test] +fn an_evicted_receipt_is_not_found_on_every_route() { + let (receipts, url, _, challenge) = served_bound_turn(); + *lock(&receipts.kept) = KeptTurns::default(); + assert!(receipts.reports.recorder().holds_turn("r1")); + let mut unproven = challenge.clone(); + unproven.proof = None; + let rows = BlockChallenge { + receipt_id: "r1".into(), + picks: Vec::new(), + proof: None, + }; + for challenge in [&challenge, &unproven] { + for route in ["/receipts/open", "/v1/receipts/open"] { + let reply = post(&url, route, challenge); + assert_eq!(reply.status(), StatusCode::NOT_FOUND, "{route}"); + assert!( + reply + .headers() + .get(turn::OPENING_SIGNATURE_HEADER) + .is_none() + ); + } + } + for route in ["/receipts/rows", "/v1/receipts/rows"] { + assert_eq!(post(&url, route, &rows).status(), StatusCode::NOT_FOUND); + } + let reply = reqwest::blocking::get(format!("{url}/receipts/r1")).expect("reply"); + assert_eq!(reply.status(), StatusCode::NOT_FOUND); +} + +/// The node's signed "cannot open" answer to `challenge`, checked against +/// the receipt. +fn signed_cannot_open(reply: Response, receipt: &Receipt, challenge: &Challenge) -> CannotOpen { + let signature = reply + .headers() + .get(turn::OPENING_SIGNATURE_HEADER) + .expect("the node signs that it cannot open") + .to_str() + .unwrap() + .to_owned(); + let bytes = reply.bytes().expect("body"); + let bound = turn::verify(receipt, None).unwrap(); + turn::verify_cannot_open(&bound, &challenge.digest(), &bytes, &signature).expect("signature"); + // it is no opening + assert!(turn::verify_opening(&bound, challenge, &bytes, &signature).is_err()); + let body: serde_json::Value = serde_json::from_slice(&bytes).expect("json"); + assert!(body["error"].as_str().is_some_and(|e| !e.is_empty())); + serde_json::from_value(body["cannot_open"].clone()).expect("a cannot-open answer") +} + +// A client tells "the node can no longer open my turn" from a request the +// node refuses: by the status, the body and the node's signature. +#[test] +fn a_turn_the_node_cannot_open_is_answered_as_such() { + let (receipts, url, receipt, challenge) = served_bound_turn(); + let recorder = receipts.reports.recorder(); + // the session ended and the stage could not pin its cells, then a + // ubatch the recorder could not follow + recorder.memory_op(MemoryOp::SeqRm, SEQ, -1, -1, -1); + recorder.pins_not_applied(); + recorder.unreceiptable("two lanes in one recurrent ubatch"); + let reply = post(&url, "/v1/receipts/open", &challenge); + assert_eq!(reply.status(), StatusCode::CONFLICT); + let cannot = signed_cannot_open(reply, &receipt, &challenge); + assert_eq!(cannot.reason, CannotOpenReason::CellsUnknown); + assert_eq!((cannot.receipt_id.as_str(), cannot.stage_index), ("r1", 0)); + + // a malformed request of the same receipt is still a plain refusal + let mut malformed = challenge.clone(); + malformed.picks[0].positions = vec![9, 4]; + let reply = post(&url, "/v1/receipts/open", &malformed); + assert_eq!(reply.status(), StatusCode::BAD_REQUEST); + assert!( + reply + .headers() + .get(turn::OPENING_SIGNATURE_HEADER) + .is_none() + ); + + // the turn left the stage's opening window + let (receipts, url, receipt, challenge) = served_bound_turn(); + receipts.reports.recorder().discard("r1"); + for route in ["/receipts/open", "/v1/receipts/open"] { + let reply = post(&url, route, &challenge); + assert_eq!(reply.status(), StatusCode::GONE, "{route}"); + let cannot = signed_cannot_open(reply, &receipt, &challenge); + assert_eq!(cannot.reason, CannotOpenReason::Expired); + } +} diff --git a/crates/skippy-serving/src/receipts/kept_turns.rs b/crates/skippy-serving/src/receipts/kept_turns.rs new file mode 100644 index 00000000..08ff0dbd --- /dev/null +++ b/crates/skippy-serving/src/receipts/kept_turns.rs @@ -0,0 +1,559 @@ +//! The turns a stage keeps a record of, by receipt id: on stage 0 the +//! receipt itself, on every stage what admitting a challenge of the turn +//! takes (the client key it is bound to, the challenges admitted so far). +//! +//! A client can challenge a bound turn for its challenge window +//! ([`CHALLENGE_PIN`]) and, once it opened it, ask for its rows for +//! [`ROWS_PIN`]. A record is protected, never dropped to make room, while +//! its turn is held firmly: for [`FIRM_PIN`] after it was kept, while a +//! challenge of it is opened ([`OPENING_PIN`] at most), and for its rows. +//! For the rest of its window the record lingers: it is kept while the byte budget has room. Records +//! past their window go oldest first, when there are more than +//! [`UNPROTECTED_TURNS`] of them or the byte budget is reached; then the +//! lingering ones, oldest first. When protected records alone fill the +//! budget, a new turn gets no receipt; no turn loses a protected record. +//! +//! A receipt id names one turn. A turn that reuses an id replaces the +//! record, and with it every challenge admitted for the old turn, unless +//! the id is still a protected turn of a client: then the new turn gets no +//! receipt, so a client cannot shadow a receipt it does not own, and a +//! receipt already signed stays the one its id opens. A client that names +//! a fresh id for every turn (`x-receipt-id`) never meets either. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Arc; +use std::time::Instant; + +use anyhow::{Result, bail}; +use skippy_receipts::attention::opening::ROWS_PIN; +use skippy_receipts::commitment::Hash; +use skippy_receipts::recorder::{CHALLENGE_PIN, FIRM_PIN, OPENING_PIN}; +use skippy_receipts::wire::{Challenge, Receipt, StageCommitment}; + +/// Bytes of records a stage keeps, at most. +pub(super) const KEPT_BYTES_BUDGET: usize = 64 << 20; +/// Records no client can challenge any more that a stage keeps, so a +/// receipt stays retrievable and a late request is told what became of its +/// turn. +pub(super) const UNPROTECTED_TURNS: usize = 256; +/// What a record costs besides its receipt and challenges. +const RECORD_BYTES: usize = 256; + +/// What became of a turn. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Outcome { + /// The turn is being committed. + Committing, + /// Stage 0: the turn's receipt. + Issued(Arc), + /// A later stage: the turn is committed here, and stage 0 holds its + /// receipt. + Committed, + /// Why the turn got no receipt. + Refused(String), +} + +/// The positions a turn committed and the commitments of the stages after +/// this one, which bound what those stages may answer. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct LaterStages { + pub position_start: u32, + pub position_end: u32, + pub commitments: Arc<[StageCommitment]>, +} + +pub(super) struct KeptTurn { + pub outcome: Outcome, + /// The client VRF key the turn is bound to; `None` for a turn nobody + /// can challenge with a proof. + pub client_key: Option<[u8; 32]>, + /// The turn's root: stage 0 knows it from the receipt it signed, a + /// later stage from the first challenge it admitted. + pub turn_root: Option, + /// The challenges admitted for the turn: one, for a bound turn. + pub challenges: Vec, + /// The digest of the opening the rows' proof is over. + pub opened: Option, + pub later: LaterStages, + kept_at: Instant, + /// When the latest challenge of the turn was admitted. + challenged_at: Option, + opened_at: Option, + bytes: usize, + /// Tells this record from an older one of the same id in `order`. + generation: u64, +} + +impl KeptTurn { + /// Whether a client can still challenge the turn, or ask for its rows. + /// A turn being committed counts until it is settled. + fn challengeable(&self, now: Instant) -> bool { + if matches!(self.outcome, Outcome::Committing) { + return true; + } + if self.client_key.is_none() || matches!(self.outcome, Outcome::Refused(_)) { + return false; + } + let until = match self.opened_at { + Some(at) => at + ROWS_PIN, + None => self.kept_at + CHALLENGE_PIN, + }; + now < until + } + + /// Whether the record is never dropped to make room: its turn is being + /// committed, a challenge of it is being opened, it was opened and its + /// rows may be asked for, or a client may still challenge it at once. + /// A challenge whose opening failed protects the record no longer than + /// an opening may take, so challenges cannot fill the budget with + /// records that nothing may drop. + fn protected(&self, now: Instant) -> bool { + let held_firmly = matches!(self.outcome, Outcome::Committing) + || self.opened_at.is_some() + || self.challenged_at.is_some_and(|at| now < at + OPENING_PIN) + || now < self.kept_at + FIRM_PIN; + held_firmly && self.challengeable(now) + } + + /// The stage opened the turn: its rows may be asked for from now. + pub(super) fn mark_opened(&mut self, digest: Option, now: Instant) { + self.opened = digest.or(self.opened); + self.opened_at = Some(now); + } + + /// Admits `challenge`, which arrived at `now`, as one of the turn's, at + /// most `limit` of them. `false` when the turn already has that many + /// others. + pub(super) fn admit(&mut self, challenge: &Challenge, limit: usize, now: Instant) -> bool { + if !self.challenges.contains(challenge) { + if self.challenges.len() >= limit { + return false; + } + self.challenges.push(challenge.clone()); + } + self.challenged_at = Some(now); + true + } +} + +/// Why a reserved record was not settled with its turn's outcome. +#[derive(Debug)] +pub(super) enum Unsettled { + /// Another turn took the receipt id meanwhile; the record is that + /// turn's. + Replaced(String), + /// The record does not fit beside those clients can still challenge; + /// it now says so. + Full(String), +} + +impl std::fmt::Display for Unsettled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (Self::Replaced(why) | Self::Full(why)) = self; + f.write_str(why) + } +} + +impl std::error::Error for Unsettled {} + +/// Names the record a [`KeptTurns::reserve`] started, for its +/// [`KeptTurns::settle`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Reservation(u64); + +pub(super) struct KeptTurns { + by_id: HashMap, + /// Receipt ids by when their record was made, oldest first. + order: VecDeque<(u64, String)>, + bytes: usize, + budget: usize, + generations: u64, +} + +impl Default for KeptTurns { + fn default() -> Self { + Self::new(KEPT_BYTES_BUDGET) + } +} + +impl KeptTurns { + pub(super) fn new(budget: usize) -> Self { + Self { + by_id: HashMap::new(), + order: VecDeque::new(), + bytes: 0, + budget, + generations: 0, + } + } + + pub(super) fn get(&self, id: &str) -> Option<&KeptTurn> { + self.by_id.get(id) + } + + pub(super) fn get_mut(&mut self, id: &str) -> Option<&mut KeptTurn> { + self.by_id.get_mut(id) + } + + /// Starts the record of a turn that is about to be committed as `id`, + /// bound to `client_key` when a client can challenge it. Fails, keeping + /// what was there, when `id` is another client's turn inside its + /// window, or when the records clients can still challenge fill the + /// budget. + pub(super) fn reserve( + &mut self, + id: &str, + client_key: Option<[u8; 32]>, + now: Instant, + ) -> Result { + if let Some(old) = self.by_id.get(id) + && old.challengeable(now) + { + if old.client_key != client_key { + bail!( + "receipt id {id} names a turn of another client that can still be challenged" + ); + } + if client_key.is_some() { + // the client may still open the turn it was signed a + // receipt for: that receipt stays the one the id opens + bail!( + "receipt id {id} names a turn this client was signed a receipt for, which \ + it can still challenge" + ); + } + } + self.remove(id); + let bytes = RECORD_BYTES + id.len(); + self.make_room(bytes, now)?; + self.generations += 1; + self.bytes += bytes; + self.order.push_back((self.generations, id.to_owned())); + self.by_id.insert( + id.to_owned(), + KeptTurn { + outcome: Outcome::Committing, + client_key, + turn_root: None, + challenges: Vec::new(), + opened: None, + later: LaterStages::default(), + kept_at: now, + challenged_at: None, + opened_at: None, + bytes, + generation: self.generations, + }, + ); + Ok(Reservation(self.generations)) + } + + /// Settles a reserved record with what became of its turn. A receipt + /// that does not fit beside the records clients can still challenge is + /// refused; the error says so. So is one whose id another turn took + /// meanwhile, whose record stays as that turn left it. + pub(super) fn settle( + &mut self, + id: &str, + reservation: Reservation, + outcome: Outcome, + turn_root: Option, + later: LaterStages, + now: Instant, + ) -> Result<(), Unsettled> { + let extra = match &outcome { + Outcome::Issued(receipt) => receipt_bytes(receipt), + Outcome::Refused(reason) => reason.len(), + Outcome::Committing | Outcome::Committed => 0, + } + std::mem::size_of_val(&*later.commitments); + let fits = self.make_room(extra, now); + let Some(kept) = self + .by_id + .get_mut(id) + .filter(|kept| kept.generation == reservation.0) + else { + return Err(Unsettled::Replaced(format!( + "receipt id {id} was taken by another turn while this one was committed" + ))); + }; + kept.kept_at = now; + if let Err(error) = fits { + let why = format!("{error:#}"); + kept.outcome = Outcome::Refused(why.clone()); + return Err(Unsettled::Full(why)); + } + kept.outcome = outcome; + kept.turn_root = turn_root; + kept.later = later; + kept.bytes += extra; + self.bytes += extra; + Ok(()) + } + + fn remove(&mut self, id: &str) { + if let Some(old) = self.by_id.remove(id) { + self.bytes -= old.bytes; + } + } + + /// Drops records no client can challenge any more, oldest first, until + /// `bytes` more fit and at most [`UNPROTECTED_TURNS`] of them are left; + /// then, while `bytes` more do not fit, the lingering ones, oldest + /// first. Fails when the protected ones leave no room. + fn make_room(&mut self, bytes: usize, now: Instant) -> Result<()> { + let by_id = &self.by_id; + self.order + .retain(|(generation, id)| by_id.get(id).is_some_and(|k| k.generation == *generation)); + let mut past = self + .by_id + .values() + .filter(|kept| !kept.challengeable(now)) + .count(); + self.drop_oldest(|turns, kept| { + let over = past >= UNPROTECTED_TURNS || turns.bytes + bytes > turns.budget; + let evict = over && !kept.challengeable(now); + past -= usize::from(evict); + evict + }); + self.drop_oldest(|turns, kept| turns.bytes + bytes > turns.budget && !kept.protected(now)); + if self.bytes + bytes > self.budget { + bail!( + "the stage keeps {} bytes of receipts clients are challenging or may challenge \ + at once, of {} at most; this turn gets none", + self.bytes, + self.budget + ); + } + Ok(()) + } + + /// Drops the records `evict` names, asked oldest first with what is + /// kept so far. + fn drop_oldest(&mut self, mut evict: impl FnMut(&Self, &KeptTurn) -> bool) { + let mut kept_order = VecDeque::with_capacity(self.order.len()); + while let Some((generation, id)) = self.order.pop_front() { + if self.by_id.get(&id).is_some_and(|kept| evict(self, kept)) { + self.remove(&id); + } else { + kept_order.push_back((generation, id)); + } + } + self.order = kept_order; + } + + #[cfg(test)] + pub(super) fn len(&self) -> usize { + self.by_id.len() + } + + #[cfg(test)] + pub(super) fn bytes(&self) -> usize { + self.bytes + } +} + +/// Bytes a kept receipt holds, about. +fn receipt_bytes(receipt: &Receipt) -> usize { + let stages: usize = receipt + .stages + .iter() + .map(|stage| 512 + stage.ubatches.len() * size_of::()) + .sum(); + size_of::() + + receipt.model.len() + + receipt.tokens.len() * size_of::() + + stages + + 1024 +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use skippy_receipts::wire::{Pick, RECEIPT_VERSION}; + + use super::*; + + const VICTIM: [u8; 32] = [1; 32]; + const OTHER: [u8; 32] = [2; 32]; + + fn receipt(id: &str, tokens: usize) -> Arc { + Arc::new(Receipt { + version: RECEIPT_VERSION, + receipt_id: id.into(), + model: "m".into(), + position_start: 0, + position_end: tokens as u32, + tokens: vec![0; tokens], + generation_start: 0, + final_token: None, + stages: Vec::new(), + binding: None, + }) + } + + fn keep(turns: &mut KeptTurns, id: &str, key: Option<[u8; 32]>, now: Instant) -> Result<()> { + let reservation = turns.reserve(id, key, now)?; + let issued = Outcome::Issued(receipt(id, 4)); + Ok(turns.settle(id, reservation, issued, None, LaterStages::default(), now)?) + } + + fn challenge(id: &str, layer: u32) -> Challenge { + Challenge { + receipt_id: id.into(), + picks: vec![Pick { + layer, + positions: vec![0], + }], + proof: None, + head: Vec::new(), + attention: Vec::new(), + } + } + + // However many turns follow a turn inside its challenge window, its + // receipt stays; past the window it goes as the oldest. + #[test] + fn a_flood_of_turns_does_not_evict_one_inside_its_window() { + let mut turns = KeptTurns::default(); + let start = Instant::now(); + keep(&mut turns, "victim", Some(VICTIM), start).unwrap(); + for i in 0..4 * UNPROTECTED_TURNS { + keep(&mut turns, &format!("flood-{i}"), Some(OTHER), start).unwrap(); + } + assert!(turns.get("victim").is_some()); + assert_eq!(turns.len(), 4 * UNPROTECTED_TURNS + 1, "all inside"); + // the window passed: the oldest go, down to the count kept + let later = start + CHALLENGE_PIN; + keep(&mut turns, "next", Some(OTHER), later).unwrap(); + assert!(turns.get("victim").is_none()); + assert_eq!(turns.len(), UNPROTECTED_TURNS); + assert!(turns.get("next").is_some()); + } + + // An opened turn stays until its rows can no longer be asked for. + #[test] + fn an_opened_turn_is_kept_for_its_rows() { + let mut turns = KeptTurns::default(); + let start = Instant::now(); + keep(&mut turns, "opened", Some(VICTIM), start).unwrap(); + let opened_at = start + CHALLENGE_PIN - Duration::from_secs(1); + let kept = turns.get_mut("opened").unwrap(); + kept.mark_opened(Some([9; 32]), opened_at); + let flood = |turns: &mut KeptTurns, now| { + for i in 0..2 * UNPROTECTED_TURNS { + keep(turns, &format!("flood-{i}"), None, now).unwrap(); + } + }; + flood(&mut turns, opened_at + ROWS_PIN - Duration::from_secs(1)); + assert_eq!(turns.get("opened").unwrap().opened, Some([9; 32])); + flood(&mut turns, opened_at + ROWS_PIN); + assert!(turns.get("opened").is_none()); + } + + // When turns that can still be challenged fill the budget, a new turn + // gets no receipt and they keep theirs. + #[test] + fn a_full_budget_refuses_new_turns() { + let start = Instant::now(); + let mut sized = KeptTurns::default(); + keep(&mut sized, "one", Some(OTHER), start).unwrap(); + let mut turns = KeptTurns::new(3 * sized.bytes() + sized.bytes() / 2); + for id in ["a", "b", "c"] { + keep(&mut turns, id, Some(OTHER), start).unwrap(); + } + let error = keep(&mut turns, "d", Some(VICTIM), start).unwrap_err(); + assert!(format!("{error:#}").contains("gets none"), "{error:#}"); + assert!(["a", "b", "c"].iter().all(|id| turns.get(id).is_some())); + assert!(turns.bytes() <= 3 * sized.bytes() + sized.bytes() / 2); + // unprotected records make room + keep(&mut turns, "d", Some(VICTIM), start + CHALLENGE_PIN).unwrap(); + assert!(turns.get("a").is_none() && turns.get("d").is_some()); + } + + // Past the time a client challenges at once, a record lingers: it is + // kept while there is room, and the oldest gives way to a new turn. One + // a client challenged stays. + #[test] + fn a_lingering_record_gives_way_to_a_new_turn_and_a_challenged_one_stays() { + let start = Instant::now(); + let mut sized = KeptTurns::default(); + keep(&mut sized, "one", Some(OTHER), start).unwrap(); + let mut turns = KeptTurns::new(3 * sized.bytes() + sized.bytes() / 2); + for id in ["a", "b", "c"] { + keep(&mut turns, id, Some(OTHER), start).unwrap(); + } + let lingering = start + FIRM_PIN; + let being_opened = turns.get_mut("a").unwrap(); + assert!(being_opened.admit(&challenge("a", 1), 1, lingering)); + keep(&mut turns, "d", Some(VICTIM), lingering).unwrap(); + assert!(turns.get("a").is_some(), "being opened"); + assert!(turns.get("b").is_none(), "the oldest lingering record"); + assert!(turns.get("c").is_some() && turns.get("d").is_some()); + // and its id stays its client's for the whole window + let error = turns.reserve("c", Some(VICTIM), lingering).unwrap_err(); + assert!(format!("{error:#}").contains("another client"), "{error:#}"); + // a challenge whose opening never ended protects its record no + // longer than an opening may take: challenges cannot fill the budget + let later = lingering + OPENING_PIN; + keep(&mut turns, "e", Some(VICTIM), later).unwrap(); + assert!(turns.get("a").is_none(), "its opening did not end in time"); + assert!(turns.get("e").is_some()); + } + + // A reused id names the new turn, with none of the old turn's + // challenges, once the old one is past its window. Inside it, the new + // turn gets no receipt, whoever asks: a signed receipt stays openable. + #[test] + fn a_reused_id_never_replaces_a_turn_inside_its_window() { + let mut turns = KeptTurns::default(); + let start = Instant::now(); + keep(&mut turns, "r", Some(VICTIM), start).unwrap(); + let kept = turns.get_mut("r").unwrap(); + assert!(kept.admit(&challenge("r", 1), 1, start)); + assert!(!kept.admit(&challenge("r", 2), 1, start), "one challenge"); + kept.mark_opened(Some([7; 32]), start); + + for shadow in [Some(OTHER), None] { + let error = turns.reserve("r", shadow, start).unwrap_err(); + assert!(format!("{error:#}").contains("another client"), "{error:#}"); + } + let kept = turns.get("r").unwrap(); + assert_eq!(kept.client_key, Some(VICTIM)); + assert_eq!(kept.challenges.len(), 1, "the victim's turn is untouched"); + + // nor the same client's: its signed receipt stays the one the id opens + let error = turns.reserve("r", Some(VICTIM), start).unwrap_err(); + assert!(format!("{error:#}").contains("signed"), "{error:#}"); + let kept = turns.get("r").unwrap(); + assert!(matches!(kept.outcome, Outcome::Issued(_))); + assert_eq!(kept.opened, Some([7; 32])); + assert_eq!(kept.challenges.len(), 1, "the first turn is untouched"); + + // past the window, the same client's new turn under the id starts afresh + let after = start + ROWS_PIN + CHALLENGE_PIN; + keep(&mut turns, "r", Some(VICTIM), after).unwrap(); + let kept = turns.get_mut("r").unwrap(); + assert!(kept.challenges.is_empty() && kept.opened.is_none()); + assert!(kept.admit(&challenge("r", 2), 1, after)); + + // a turn settles only the record it reserved: an unbound turn + // under an id nobody can challenge is replaced + let start = after + ROWS_PIN + CHALLENGE_PIN; + let stale = turns.reserve("r", None, start).unwrap(); + let current = turns.reserve("r", None, start).unwrap(); + let committed = |turns: &mut KeptTurns, reservation| { + let later = LaterStages::default(); + turns.settle("r", reservation, Outcome::Committed, None, later, start) + }; + assert!(committed(&mut turns, stale).is_err()); + assert_eq!(turns.get("r").unwrap().outcome, Outcome::Committing); + committed(&mut turns, current).unwrap(); + + // past its window an id is anyone's + let later = start + ROWS_PIN + CHALLENGE_PIN; + keep(&mut turns, "r", Some(OTHER), later).unwrap(); + assert_eq!(turns.get("r").unwrap().client_key, Some(OTHER)); + assert!(turns.get("never").is_none()); + } +} diff --git a/crates/skippy-serving/src/receipts/kv_cache.rs b/crates/skippy-serving/src/receipts/kv_cache.rs new file mode 100644 index 00000000..3bc08f78 --- /dev/null +++ b/crates/skippy-serving/src/receipts/kv_cache.rs @@ -0,0 +1,63 @@ +//! Whether a stage's KV cache is one an audit covers. +//! +//! A stage with a quantized KV cache (`cache_type_k` or `cache_type_v` of +//! q8_0 or q4_0) issues no receipts: an honest one fails the loose attention +//! check in about 1 audit in 4.5 ([`skippy_receipts::cache_types`]). So its +//! recorder does not start, the stage serves every request as usual, and +//! an embedder that asks whether the runtime issues receipts hears that it +//! issues none. A turn that stored quantized rows all the same is refused +//! again when it commits (`skippy_receipts::recorder`). + +use skippy_protocol::StageConfig; +use skippy_receipts::cache_types; + +/// Why a stage with `config`'s KV cache issues no receipts, when it issues +/// none. +pub(super) fn unaudited(config: &StageConfig) -> Option { + unaudited_types(&config.cache_type_k, &config.cache_type_v) +} + +/// [`unaudited`] for the cache types of the keys and the values, as a stage +/// config names them. A name the runtime does not know is not judged here: +/// the model does not load with it. +fn unaudited_types(cache_type_k: &str, cache_type_v: &str) -> Option { + [ + ("cache_type_k", cache_type_k), + ("cache_type_v", cache_type_v), + ] + .into_iter() + .find_map(|(setting, name)| { + let ggml_type = i32::try_from(skippy_runtime::parse_cache_type(name).ok()?).ok()?; + cache_types::audited(ggml_type).is_none().then(|| { + format!( + "{setting} is {}, and no audit covers a quantized KV cache", + cache_types::name(ggml_type) + ) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::unaudited_types; + + #[test] + fn only_a_cache_that_is_not_quantized_gets_receipts() { + for (k, v) in [("f16", "f16"), ("", ""), ("F16", "f16")] { + assert_eq!(unaudited_types(k, v), None, "{k} {v}"); + } + for (k, v, named) in [ + ("q8_0", "q8_0", "cache_type_k is q8_0"), + ("f16", "q8_0", "cache_type_v is q8_0"), + ("q4_0", "f16", "cache_type_k is q4_0"), + ("f16", "q4", "cache_type_v is q4_0"), + ("q8", "f16", "cache_type_k is q8_0"), + ] { + let reason = unaudited_types(k, v).unwrap(); + assert!(reason.contains(named), "{k} {v}: {reason}"); + assert!(reason.contains("quantized KV cache"), "{reason}"); + } + // the runtime refuses such a name when it loads the model + assert_eq!(unaudited_types("auto", "f16"), None); + } +} diff --git a/crates/skippy-serving/src/receipts/native.rs b/crates/skippy-serving/src/receipts/native.rs new file mode 100644 index 00000000..0d8bc192 --- /dev/null +++ b/crates/skippy-serving/src/receipts/native.rs @@ -0,0 +1,619 @@ +//! Adapters between the native receipt recorder and replay, and the +//! [`Recorder`]. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::time::{Duration, Instant}; + +use super::StageReplayer; + +use anyhow::{Result, bail}; +use skippy_receipts::attention::{ + AttentionDescriptor, AttentionLayout, AttentionOp, OutputRotation, Window, q_rounding, +}; +use skippy_receipts::commitment::ValueDigest; +use skippy_receipts::layer_tensors::{TensorColumn, TensorKind, UbatchColumns}; +use skippy_receipts::recorder::Recorder; +use skippy_receipts::recorder::{ + AnchorValue, KvCell, PrefixCell, ReplayAnchor, ReplayScope, ReplaySeed, ReplayStep, + ReplayedLayer, ReplayedPosition, Replayer, StageInput, StoredRows, UbatchRecord, +}; +use skippy_runtime::{ + ReceiptAnchorRef, ReceiptAttentionOp, ReceiptAttentionWindow, ReceiptMemoryEvent, + ReceiptRecorderSink, ReceiptReplayScope, ReceiptReplayStepRef, ReceiptReplayer, + ReceiptTensorView, RecordedUbatch, +}; + +use super::report_queue::Report; +use crate::runtime_state::RuntimeState; +use crate::runtime_state::panic_recovery::lock_runtime; + +/// The tensors of a native ubatch, by layer, kind and index. A tensor with +/// fewer columns than tokens covers only the output rows. +struct ViewColumns<'a> { + output_index: Vec>, + tensors: HashMap<(u32, TensorKind, u32), ReceiptTensorView<'a>>, + counts: HashMap<(u32, TensorKind), u32>, +} + +impl<'a> ViewColumns<'a> { + fn new(output: &[i8], tensors: impl Iterator>) -> Self { + let mut next = 0; + let output_index = output + .iter() + .map(|&flag| { + (flag != 0).then(|| { + next += 1; + next - 1 + }) + }) + .collect(); + let tensors: HashMap<_, _> = tensors + .filter_map(|t| Some(((t.layer, TensorKind::from_code(t.kind)?, t.index), t))) + .collect(); + let mut counts: HashMap<(u32, TensorKind), u32> = HashMap::new(); + for &(layer, kind, index) in tensors.keys() { + let count = counts.entry((layer, kind)).or_default(); + *count = (*count).max(index + 1); + } + Self { + output_index, + tensors, + counts, + } + } +} + +impl UbatchColumns for ViewColumns<'_> { + fn count(&self, layer: u32, kind: TensorKind) -> u32 { + self.counts.get(&(layer, kind)).copied().unwrap_or(0) + } + + fn column( + &self, + layer: u32, + kind: TensorKind, + index: u32, + col: usize, + ) -> Option> { + let tensor = self.tensors.get(&(layer, kind, index))?; + let j = if kind == TensorKind::MixingState { + sequence_column(self.output_index.len(), tensor.n_cols, col)? + } else if tensor.n_cols == self.output_index.len() { + col + } else { + (*self.output_index.get(col)?)? + }; + (j < tensor.n_cols).then(|| TensorColumn { + ggml_type: tensor.ggml_type, + flags: tensor.flags, + name: tensor.name, + bytes: tensor.column(j), + digest: tensor.column_digest(j).map(|digest| ValueDigest { + len: tensor.row_bytes as u32, + digest, + }), + }) + } +} + +/// The state column of the token at `col`: a ubatch's sequences are runs of +/// `n_tokens / n_seqs` tokens, and each holds its state at its first token. +fn sequence_column(n_tokens: usize, n_seqs: usize, col: usize) -> Option { + let per_seq = n_tokens.checked_div(n_seqs).filter(|&n| n > 0)?; + col.is_multiple_of(per_seq).then_some(col / per_seq) +} + +/// Records one native ubatch. The ubatch is dropped once its leaves are +/// hashed, which lets the runtime deliver the next one. +pub(super) fn apply_ubatch(recorder: &Recorder, mut ubatch: RecordedUbatch) { + let record = UbatchRecord { + token: std::mem::take(&mut ubatch.token), + seq: std::mem::take(&mut ubatch.seq), + pos: std::mem::take(&mut ubatch.pos), + output: std::mem::take(&mut ubatch.output), + cell: std::mem::take(&mut ubatch.cell), + n_kv: ubatch.n_kv, + input: ubatch + .input + .take() + .map(|(rows, row_bytes, ggml_type)| StageInput { + rows, + row_bytes, + ggml_type, + }), + }; + let columns = ViewColumns::new(&record.output, ubatch.tensors()); + recorder.record_ubatch(record, &columns); +} + +/// Queues the native recorder's reports for the stage's +/// [`super::StageReceipts`]. The model owns the sink for as long as it +/// lives, and the receipts hold the model for their replays, so the sink +/// only points at the receipts: the stage owns them, and a model that is +/// being unloaded reports into nothing. +pub(super) struct RecorderSink(Weak); + +impl RecorderSink { + pub(super) fn new(receipts: &Arc) -> Self { + Self(Arc::downgrade(receipts)) + } + + fn push(&self, report: Report) { + if let Some(receipts) = self.0.upgrade() { + receipts.reports.push(report); + } + } +} + +impl ReceiptRecorderSink for RecorderSink { + fn ubatch(&self, ubatch: RecordedUbatch) { + self.push(Report::Ubatch(ubatch)); + } + + fn unreceiptable(&self, reason: &str) { + self.push(Report::Unreceiptable(reason.to_string())); + } + + fn unrecorded_ubatch(&self, reason: &str) { + self.push(Report::UnrecordedUbatch(reason.to_string())); + } + + fn memory(&self, event: &ReceiptMemoryEvent) { + self.push(Report::Memory(*event)); + } + + fn state(&self, seq: i32, state: Option<&[u8]>) { + self.push(Report::State { + seq, + state: state.map(<[u8]>::to_vec), + }); + } +} + +/// The scratch context is freed after this long without a replay. +const SCRATCH_IDLE: Duration = Duration::from_secs(60); + +/// When the scratch context was last used, while it may exist. +#[derive(Default)] +struct ScratchUse(Mutex>); + +/// What to do about the scratch context at some time. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ScratchDue { + /// Free it: it has been idle long enough. + Free, + /// Look again then. + At(Instant), + /// Nothing used it since it was freed. + Unused, +} + +impl ScratchUse { + fn lock(&self) -> std::sync::MutexGuard<'_, Option> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// A seed or replay may have created the context, or just used it. + fn used(&self, now: Instant) { + *self.lock() = Some(now); + } + + /// What is due at `now`. A context that is due to be freed counts as + /// unused from here; a use after this marks it again. + fn due(&self, now: Instant) -> ScratchDue { + let mut used = self.lock(); + match *used { + None => ScratchDue::Unused, + Some(at) if now.saturating_duration_since(at) >= SCRATCH_IDLE => { + *used = None; + ScratchDue::Free + } + Some(at) => ScratchDue::At(at + SCRATCH_IDLE), + } + } +} + +/// Replays turns in the stage model's scratch context, and frees the +/// context once replays stop, since it holds a second KV cache. +pub(super) struct NativeReplayer { + replayer: ReceiptReplayer, + /// The stage, kept idle while a replay's prefix is copied from it. + runtime: Weak>, + receipts: Weak, + /// Held from seeding the scratch context to the end of the replay, so + /// another replay does not take the seeded cells. + serial: Mutex<()>, + scratch: ScratchUse, +} + +impl NativeReplayer { + pub(super) fn new( + replayer: ReceiptReplayer, + runtime: Weak>, + receipts: Weak, + ) -> Self { + Self { + replayer, + runtime, + receipts, + serial: Mutex::new(()), + scratch: ScratchUse::default(), + } + } + + /// The stage and its receipts, while the stage is loaded. + fn stage(&self) -> Result<(Arc>, Arc)> { + match (self.runtime.upgrade(), self.receipts.upgrade()) { + (Some(runtime), Some(receipts)) => Ok((runtime, receipts)), + _ => bail!("the stage is shutting down"), + } + } + + /// Notes that the scratch context may exist from now, so the stage's + /// upkeep frees it once it has been idle. + fn scratch_used(&self, receipts: &super::StageReceipts) { + self.scratch.used(Instant::now()); + receipts.poke_upkeep(); + } + + /// Copies the prefix cells of `seed` into the scratch context, with the + /// stage idle and every report of what it computed applied, once the + /// recorder confirms the cells still hold the prefix. + /// + /// Every lane's decode step needs the runtime lock this holds, so only + /// what must see an idle stage runs under it: the last reports, the + /// check of the cells, and the native copy. The copy creates the + /// scratch context when there is none, or one too small, which the + /// native call does not let a caller do beforehand. + fn seed(&self, seq: i32, seed: &ReplaySeed) -> Result<()> { + let (runtime, receipts) = self.stage()?; + let (cells, positions) = (seed.indices(), seed.positions()); + // the reports made so far are applied without the lock; only those + // made while it is awaited are left for under it + receipts.reports.wait_applied(); + // the seed below may create the context and then fail + self.scratch_used(&receipts); + let mut state = lock_runtime(&runtime); + receipts.reports.wait_applied(); + receipts.reports.recorder().check_seed(seed)?; + let idle = state.model.idle(); + self.replayer + .seed(&idle, seq, &cells, &positions, seed.n_cells)?; + match &seed.state { + Some(state) => self.replayer.seed_state(&idle, seq, state), + None => Ok(()), + } + } +} + +impl NativeReplayer { + /// The rows of `layer` in `cells`, read [`READ_CHUNK_CELLS`] cells at a + /// time with the stage idle, each chunk once `check` confirms its cells + /// still hold what the turn read or wrote. + /// + /// Every lane's decode step needs the runtime lock, so a long context is + /// not read under one hold of it: the lanes decode between chunks. That + /// is safe because a chunk's rows are copied out under the check that + /// covers them; a later write of a cell read before does not change + /// what was read. + fn read_checked_rows( + &self, + layer: u32, + cells: &[PrefixCell], + check: fn(&Recorder, &[PrefixCell]) -> Result<()>, + ) -> Result> { + let (runtime, receipts) = self.stage()?; + let stream = cells.first().map_or(0, |c| c.stream); + if cells.iter().any(|c| c.stream != stream) { + bail!("the cells to read are in several streams"); + } + // a sequence of the stream: stream s holds sequence s when the cache + // has a stream per sequence, and a unified cache's one holds them all + let seq = i32::try_from(stream)?; + let mut out: Vec = Vec::new(); + for chunk in cells.chunks(READ_CHUNK_CELLS) { + let indices: Vec = chunk.iter().map(|c| c.cell).collect(); + // as for a seed: the lock every decode step needs is held only + // for the last reports, the check of the cells and the read + receipts.reports.wait_applied(); + let rows = { + let mut state = lock_runtime(&runtime); + receipts.reports.wait_applied(); + check(receipts.reports.recorder(), chunk)?; + let idle = state.model.idle(); + self.replayer.read_rows(&idle, layer, seq, &indices)? + }; + append_rows(&mut out, rows)?; + } + Ok(out) + } +} + +/// Cells whose rows are read under one hold of the runtime lock: with +/// 8 KV heads of 128 dimensions in f16, 2 MiB of K and V rows a layer. +const READ_CHUNK_CELLS: usize = 1024; + +/// Appends a chunk's rows, one [`StoredRows`] per stored row of the layer, +/// to those of the chunks before it. +fn append_rows( + out: &mut Vec, + rows: Vec, +) -> Result<()> { + if out.is_empty() { + out.extend(rows.into_iter().map(|r| StoredRows { + ggml_type: r.ggml_type, + row_bytes: r.row_bytes, + values: r.values, + })); + return Ok(()); + } + if rows.len() != out.len() { + bail!("the stage read a different number of stored rows per chunk"); + } + for (kept, r) in out.iter_mut().zip(rows) { + if (kept.ggml_type, kept.row_bytes) != (r.ggml_type, r.row_bytes) { + bail!("the stage read stored rows of another type in a later chunk"); + } + kept.values.extend_from_slice(&r.values); + } + Ok(()) +} + +impl StageReplayer for NativeReplayer { + fn release_idle(&self, now: Instant) -> Option { + release_between_replays(&self.serial, &self.scratch, now, || { + self.replayer.release_scratch() + }) + } +} + +/// Frees the scratch context once it has been idle, never during a replay. +/// +/// A replay holds `serial` from its seed to its end, and marks the context +/// used only at those two points, so a replay longer than [`SCRATCH_IDLE`] +/// would otherwise see the context freed between its seed and its replay. +/// The idle time is checked under `serial`; while a replay holds it, the +/// context is left alone and looked at again later. +fn release_between_replays( + serial: &Mutex<()>, + scratch: &ScratchUse, + now: Instant, + release: impl FnOnce() -> Result<()>, +) -> Option { + let _serial = match serial.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return Some(now + SCRATCH_IDLE), + }; + match scratch.due(now) { + ScratchDue::Unused => None, + ScratchDue::At(at) => Some(at), + ScratchDue::Free => { + if let Err(error) = release() { + tracing::warn!("receipts: cannot free the replay context: {error:#}"); + } + None + } + } +} + +impl Replayer for NativeReplayer { + fn replay( + &self, + seq: i32, + layers: &[u32], + scope: ReplayScope<'_>, + seed: Option<&ReplaySeed>, + steps: &[ReplayStep], + ) -> Result> { + let _serial = self.serial.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(seed) = seed { + self.seed(seq, seed)?; + } + let refs: Vec> = steps + .iter() + .map(|step| match step { + ReplayStep::Decode { + record, + capture, + mixing, + } => ReceiptReplayStepRef::Decode { + token: &record.token, + seq: &record.seq, + pos: &record.pos, + output: &record.output, + cell: &record.cell, + n_kv: record.n_kv, + input: record + .input + .as_ref() + .map(|input| (input.rows.as_slice(), input.row_bytes, input.ggml_type)), + capture: !capture.is_empty() || !mixing.is_empty(), + }, + ReplayStep::SeqRm { p0, p1 } => ReceiptReplayStepRef::SeqRm { p0: *p0, p1: *p1 }, + }) + .collect(); + let anchors: Vec> = match scope { + ReplayScope::Anchored(anchors) => anchors.iter().map(anchor_ref).collect(), + _ => Vec::new(), + }; + let scope = match scope { + ReplayScope::Full => ReceiptReplayScope::Full, + ReplayScope::Committed => ReceiptReplayScope::Committed, + ReplayScope::Anchored(_) => ReceiptReplayScope::Anchored(&anchors), + }; + let mut out = Vec::new(); + let replayed = self + .replayer + .replay(seq, layers, &scope, &refs, &mut |view| { + let Some(ReplayStep::Decode { + capture, mixing, .. + }) = view.step.and_then(|i| steps.get(i)) + else { + bail!("replay captured an unexpected step"); + }; + let columns = ViewColumns::new(view.output, view.tensors.iter().copied()); + let attention = attention_by_layer(&view.attention); + for (col, (&s, &p)) in view.seq.iter().zip(view.pos).enumerate() { + let Ok(position) = u32::try_from(p) else { + continue; + }; + if s == seq && capture.contains(&position) { + for &layer in layers { + let mut values = ReplayedLayer::from_columns(layer, &columns, col)?; + values.attention = attention.get(&layer).cloned().unwrap_or_default(); + out.push((position, layer, values)); + } + } else if s == seq && mixing.contains(&position) { + for &layer in layers { + let values = ReplayedLayer::from_mixing_columns(layer, &columns, col); + out.push((position, layer, values)); + } + } + } + Ok(()) + }); + if let Some(receipts) = self.receipts.upgrade() { + self.scratch_used(&receipts); + } + replayed?; + Ok(out) + } + + fn read_rows(&self, layer: u32, cells: &[PrefixCell]) -> Result> { + self.read_checked_rows(layer, cells, Recorder::check_cells) + } + + fn read_rows_to_check(&self, layer: u32, cells: &[PrefixCell]) -> Result> { + self.read_checked_rows(layer, cells, Recorder::check_unseen_overwrite) + } + + fn pin_cells(&self, cells: &[KvCell]) -> Result<()> { + let streams: Vec = cells.iter().map(|c| c.stream).collect(); + let cells: Vec = cells.iter().map(|c| c.cell).collect(); + self.replayer.pin_cells(&streams, &cells) + } +} + +fn anchor_ref(anchor: &ReplayAnchor) -> ReceiptAnchorRef<'_> { + let (kind, index) = match anchor.value { + AnchorValue::Residual => (TensorKind::Residual, 0), + AnchorValue::MixingOutput(index) => (TensorKind::MixingOutput, index), + }; + ReceiptAnchorRef { + step: anchor.step, + seq: anchor.seq, + pos: anchor.pos, + layer: anchor.layer, + kind: kind.code(), + index, + values: &anchor.values, + } +} + +/// A replay's attention ops, by layer. +fn attention_by_layer(ops: &[ReceiptAttentionOp]) -> HashMap> { + let mut by_layer: HashMap> = HashMap::new(); + for op in ops { + by_layer + .entry(op.layer) + .or_default() + .push(attention_descriptor(op)); + } + by_layer +} + +/// An attention op as the receipt check describes it. +fn attention_descriptor(op: &ReceiptAttentionOp) -> AttentionDescriptor { + let a = op.op.as_ref().map_err(Clone::clone)?; + Ok(AttentionLayout { + layer: op.layer, + op: AttentionOp { + n_head: a.n_head, + n_head_kv: a.n_head_kv, + head_dim_k: a.head_dim_k, + head_dim_v: a.head_dim_v, + scale: f64::from(a.scale), + softcap: f64::from(a.softcap), + sinks: a.sinks.clone(), + output_rotation: a + .output_rotation + .clone() + .map(|(n, matrix)| OutputRotation { n, matrix }), + q_rounding: a + .q_rounding + .map(q_rounding) + .transpose() + .map_err(|e| e.to_string())?, + window: match a.window { + ReceiptAttentionWindow::Causal => Window::Causal, + ReceiptAttentionWindow::Sliding(n) => Window::Sliding(n), + ReceiptAttentionWindow::Chunked(n) => Window::Chunked(n), + }, + }, + q_input: a.q_input, + k_store: a.k_store, + v_store: a.v_store, + output: a.output, + output_gate: a.output_gate, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + // The scratch context is freed once it has been idle, whether a replay + // or only a seed used it: a seed that fails after it created the + // context marks it used all the same. + #[test] + fn a_used_scratch_context_is_due_once_idle() { + let scratch = ScratchUse::default(); + let start = Instant::now(); + assert_eq!(scratch.due(start + SCRATCH_IDLE), ScratchDue::Unused); + scratch.used(start); + let early = start + SCRATCH_IDLE / 2; + assert_eq!(scratch.due(early), ScratchDue::At(start + SCRATCH_IDLE)); + // a later use moves the time + scratch.used(early); + assert_eq!( + scratch.due(start + SCRATCH_IDLE), + ScratchDue::At(early + SCRATCH_IDLE) + ); + assert_eq!(scratch.due(early + SCRATCH_IDLE), ScratchDue::Free); + assert_eq!(scratch.due(early + SCRATCH_IDLE), ScratchDue::Unused); + } + + // A replay that outlasts the idle time keeps the context it seeded: + // the upkeep does not free it until the replay lets go. + #[test] + fn a_running_replay_keeps_its_scratch_context() { + let (serial, scratch) = (Mutex::new(()), ScratchUse::default()); + let start = Instant::now(); + scratch.used(start); + let late = start + SCRATCH_IDLE * 2; + let freed = std::cell::Cell::new(0); + let release = || { + freed.set(freed.get() + 1); + Ok(()) + }; + { + let _replay = serial.lock().unwrap(); + let next = release_between_replays(&serial, &scratch, late, release); + assert_eq!(next, Some(late + SCRATCH_IDLE)); + assert_eq!(freed.get(), 0); + } + // once it ends, the idle context is freed + assert_eq!( + release_between_replays(&serial, &scratch, late, release), + None + ); + assert_eq!(freed.get(), 1); + assert_eq!( + release_between_replays(&serial, &scratch, late, release), + None + ); + assert_eq!(freed.get(), 1); + } +} diff --git a/crates/skippy-serving/src/receipts/opening_queue.rs b/crates/skippy-serving/src/receipts/opening_queue.rs new file mode 100644 index 00000000..0309256c --- /dev/null +++ b/crates/skippy-serving/src/receipts/opening_queue.rs @@ -0,0 +1,284 @@ +//! Which challenge or rows request a stage works on next, and which it +//! turns away. +//! +//! An opening replays a turn and a rows request reads stored rows; both +//! hold the runtime's lock while the stage serves requests, so a stage +//! works on [`RUNNING`] of them at a time. The others wait in a bounded +//! queue: at most [`MAX_WAITING`] in all and [`MAX_WAITING_PER_KEY`] of one +//! client key, each for at most [`MAX_WAIT`]. When several wait, the key +//! that has used the least time since the stage was last idle goes next, +//! so a client key that sends many challenges cannot hold the stage while +//! another client's challenge waits. The turns bound to no key count as one +//! key. +//! +//! A request past these bounds gets [`Busy`]: HTTP 503 with a +//! `Retry-After`. It is not signed, as a cannot-open answer is: the +//! receipt format has no busy answer a node signs. The challenge is not +//! admitted, so the client can send it again. + +use std::collections::HashMap; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +/// Openings and rows requests a stage works on at a time. +pub(super) const RUNNING: usize = 1; +/// Requests that wait for the stage, at most. With [`RUNNING`] and replays +/// of about a second each, the last one waits a few seconds. The turn a +/// waiting challenge names stays pinned while it waits and is opened +/// (`Recorder::hold_for_opening`). +pub(super) const MAX_WAITING: usize = 8; +/// Requests of one client key that wait, at most: a challenge and its rows +/// request, so one key cannot fill the queue. +pub(super) const MAX_WAITING_PER_KEY: usize = 2; +/// How long a request waits, at most, before it gets [`Busy`]: an answer +/// later than this would reach a client past the challenge window anyway. +pub(super) const MAX_WAIT: Duration = Duration::from_secs(8); +/// When a turned-away client should try again. +pub(super) const RETRY_AFTER: Duration = Duration::from_secs(2); + +/// The client key a request is queued under; `None` for a turn bound to no +/// key. +pub(super) type QueueKey = Option<[u8; 32]>; + +/// The stage turned a request away before admitting it; the client may +/// send it again after `retry_after`. +#[derive(Debug)] +pub(super) struct Busy { + pub reason: String, + pub retry_after: Duration, +} + +impl std::fmt::Display for Busy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}; try again in {} s", + self.reason, + self.retry_after.as_secs() + ) + } +} + +impl std::error::Error for Busy {} + +fn busy(reason: impl Into) -> anyhow::Error { + anyhow::Error::new(Busy { + reason: reason.into(), + retry_after: RETRY_AFTER, + }) +} + +struct Waiter { + ticket: u64, + key: QueueKey, +} + +#[derive(Default)] +struct QueueState { + running: usize, + /// In arrival order. + waiting: Vec, + /// By key, the time its requests ran since the stage was last idle. + used: HashMap, + next_ticket: u64, +} + +impl QueueState { + /// The waiter that goes next: of the key that used the least time, the + /// one that came first. + fn next(&self) -> Option { + self.waiting + .iter() + .min_by_key(|w| (self.used.get(&w.key).copied().unwrap_or_default(), w.ticket)) + .map(|w| w.ticket) + } + + fn leave(&mut self, ticket: u64) { + self.waiting.retain(|w| w.ticket != ticket); + } +} + +#[derive(Default)] +pub(super) struct OpeningQueue { + state: Mutex, + changed: Condvar, +} + +/// A request's turn at the stage; the next one goes when it is dropped. +pub(super) struct Slot<'a> { + queue: &'a OpeningQueue, + key: QueueKey, + started: Instant, +} + +impl Drop for Slot<'_> { + fn drop(&mut self) { + let mut state = self.queue.lock(); + state.running -= 1; + *state.used.entry(self.key).or_default() += self.started.elapsed(); + if state.running == 0 && state.waiting.is_empty() { + // the stage is idle: every key starts even again + state.used.clear(); + } + self.queue.changed.notify_all(); + } +} + +impl OpeningQueue { + fn lock(&self) -> MutexGuard<'_, QueueState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits for a request of `key` to have its turn at the stage, or + /// fails with [`Busy`]. + pub(super) fn enter(&self, key: QueueKey) -> anyhow::Result> { + self.enter_within(key, MAX_WAIT) + } + + fn enter_within(&self, key: QueueKey, wait: Duration) -> anyhow::Result> { + let mut state = self.lock(); + if state.running < RUNNING && state.waiting.is_empty() { + return Ok(self.start(&mut state, key)); + } + if state.waiting.len() >= MAX_WAITING { + return Err(busy(format!( + "the stage is opening other turns, and {MAX_WAITING} requests wait" + ))); + } + if state.waiting.iter().filter(|w| w.key == key).count() >= MAX_WAITING_PER_KEY { + return Err(busy(format!( + "{MAX_WAITING_PER_KEY} requests of this client key wait already" + ))); + } + let ticket = state.next_ticket; + state.next_ticket += 1; + state.waiting.push(Waiter { ticket, key }); + let deadline = Instant::now() + wait; + loop { + if state.running < RUNNING && state.next() == Some(ticket) { + state.leave(ticket); + return Ok(self.start(&mut state, key)); + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + state.leave(ticket); + // another waiter may be next now + self.changed.notify_all(); + return Err(busy(format!( + "the stage was opening other turns for {} s", + wait.as_secs_f64() + ))); + } + state = self + .changed + .wait_timeout(state, left) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + } + + fn start(&self, state: &mut QueueState, key: QueueKey) -> Slot<'_> { + state.running += 1; + Slot { + queue: self, + key, + started: Instant::now(), + } + } + + #[cfg(test)] + pub(super) fn waiting(&self) -> usize { + self.lock().waiting.len() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::mpsc; + + use super::*; + + const A: QueueKey = Some([1; 32]); + const B: QueueKey = Some([2; 32]); + + fn is_busy(result: &anyhow::Result>) -> bool { + result + .as_ref() + .err() + .is_some_and(|e| e.downcast_ref::().is_some()) + } + + /// Waits until `n` requests wait in `queue`. + fn until_waiting(queue: &OpeningQueue, n: usize) { + let deadline = Instant::now() + Duration::from_secs(30); + while queue.waiting() != n { + assert!( + Instant::now() < deadline, + "{} wait, not {n}", + queue.waiting() + ); + std::thread::yield_now(); + } + } + + // One key's flood waits behind no more than its share, and the + // challenge of another key goes before the flood's next request. + #[test] + fn a_key_that_floods_the_stage_does_not_starve_another_key() { + let queue = Arc::new(OpeningQueue::default()); + let running = queue.enter(A).unwrap(); + let (order, finished) = mpsc::channel(); + let waiter = |key: QueueKey, name: &'static str| { + let (queue, order) = (queue.clone(), order.clone()); + std::thread::spawn(move || { + let slot = queue.enter_within(key, Duration::from_secs(60)); + order.send((name, slot.is_ok())).unwrap(); + }) + }; + let flood = [waiter(A, "a1"), waiter(A, "a2")]; + until_waiting(&queue, 2); + // past its share, the flood is turned away at once + assert!(is_busy(&queue.enter_within(A, Duration::from_secs(60)))); + let other = waiter(B, "b"); + until_waiting(&queue, 3); + drop(running); + for thread in flood.into_iter().chain([other]) { + thread.join().unwrap(); + } + let order: Vec<_> = finished.try_iter().collect(); + assert_eq!(order[0], ("b", true), "{order:?}"); + assert!(order.iter().all(|(_, ok)| *ok), "{order:?}"); + } + + // The queue is bounded in all, and a request that waits too long is + // turned away; a turned-away request leaves no trace. + #[test] + fn a_full_queue_and_a_long_wait_answer_busy() { + let queue = Arc::new(OpeningQueue::default()); + let running = queue.enter(None).unwrap(); + let threads: Vec<_> = (0..MAX_WAITING) + .map(|i| { + let queue = queue.clone(); + std::thread::spawn(move || { + let key = Some([u8::try_from(i).unwrap() + 10; 32]); + queue + .enter_within(key, Duration::from_secs(60)) + .map(|_| ()) + .is_ok() + }) + }) + .collect(); + until_waiting(&queue, MAX_WAITING); + let error = queue.enter(B).err().unwrap(); + let busy = error.downcast_ref::().unwrap(); + assert_eq!(busy.retry_after, RETRY_AFTER); + drop(running); + assert!(threads.into_iter().all(|t| t.join().unwrap())); + let running = queue.enter(A).unwrap(); + assert!(is_busy(&queue.enter_within(B, Duration::ZERO))); + assert_eq!(queue.waiting(), 0); + drop(running); + assert!(queue.enter(B).is_ok()); + } +} diff --git a/crates/skippy-serving/src/receipts/prefix_tests.rs b/crates/skippy-serving/src/receipts/prefix_tests.rs new file mode 100644 index 00000000..91838b18 --- /dev/null +++ b/crates/skippy-serving/src/receipts/prefix_tests.rs @@ -0,0 +1,70 @@ +//! A turn that continues a cached prefix, on the fixture chain of +//! `tests.rs`: its turn at positions 4..10 continues four positions that an +//! earlier turn of the session computed. + +use skippy_receipts::binding::{verify_paths, verify_shape}; + +use super::{Chain, POSITIONS, SESSION, chain, challenge, session_turn, turn}; +use crate::receipts::TurnTokens; + +// The fixture's turn continues a prefix of four positions. A challenge +// picks two of them, and every stage opens them by a replay of the ubatch +// that wrote them. +#[test] +fn opens_positions_of_the_cached_prefix_on_every_stage() { + let Chain { + stage0, + probe0, + probe1, + .. + } = chain(); + let receipt = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + verify_shape(&receipt, 4).expect("shape"); + let prefix = |stage: usize| receipt.stages[stage].prefix.clone().expect("a prefix"); + assert_eq!((prefix(0).positions, prefix(1).positions), (4, 4)); + assert!(prefix(0).tokens.is_some() && prefix(1).tokens.is_none()); + + let mut challenge = challenge("r1", &[1, 3]); + for pick in &mut challenge.picks { + pick.positions = vec![1, 3, 7, 9]; + } + skippy_receipts::challenge::check_shape(&challenge, &receipt).expect("a draw's shape"); + let opening = stage0.open(&challenge, None).expect("opening"); + verify_paths(&receipt, &challenge, &opening).expect("paths verify"); + assert_eq!(opening.stages[0].prefix_tokens, vec![100, 101, 102, 103]); + assert!(opening.stages[1].prefix_tokens.is_empty()); + for stage in &opening.stages { + let opened: Vec = stage.prefix.iter().map(|p| p.position).collect(); + assert_eq!(opened, [1, 3]); + } + // the turn, and the one ubatch that wrote both prefix positions + assert_eq!((probe0.replays(), probe1.replays()), (2, 2)); + + // three positions of the prefix are more than a draw picks + for pick in &mut challenge.picks { + pick.positions = vec![0, 1, 3, 7]; + } + let error = stage0.open(&challenge, None).expect_err("no draw's shape"); + assert!(format!("{error:#}").contains("of the prefix"), "{error:#}"); +} + +// Receipts forbid the reuse of generated tokens, so a prefix holds only +// what a request fed. A turn whose prefix is longer than its prompt would +// hold sampled tokens that no head check covers: it gets no receipt. +#[test] +fn a_prefix_longer_than_the_prompt_gets_no_receipt() { + let Chain { stage0, .. } = chain(); + let tokens = TurnTokens { + generation_start: POSITIONS.start - 1, + ..turn() + }; + let error = stage0 + .finish_turn("r1", SESSION, session_turn(), tokens, None) + .expect_err("a prefix past the prompt"); + assert!( + format!("{error:#}").contains("longer than its prompt"), + "{error:#}" + ); +} diff --git a/crates/skippy-serving/src/receipts/refusal.rs b/crates/skippy-serving/src/receipts/refusal.rs new file mode 100644 index 00000000..e1925ecb --- /dev/null +++ b/crates/skippy-serving/src/receipts/refusal.rs @@ -0,0 +1,184 @@ +//! Why a stage did not answer a receipts request, as its caller needs to +//! tell: an unknown receipt, a stage without receipts, a turn the stage +//! can no longer open, or a request it refuses. +//! +//! The reasons travel as errors inside a stage, as reply kinds between +//! stages ([`ReceiptsReply`]) and as HTTP statuses to a client, and keep +//! their meaning along a chain: what a later stage answered is what stage +//! 0 answers its client. + +use skippy_protocol::binary::{MAX_STAGE_RECEIPTS_REFUSAL_BYTES, ReceiptsReply}; +use skippy_receipts::wire::CannotOpen; + +/// A request names a receipt the stage holds no record of: one it never +/// issued, or one it dropped after its challenge window. +#[derive(Debug)] +pub(super) struct NotFound(pub String); + +impl std::fmt::Display for NotFound { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for NotFound {} + +/// The stage issues no receipts: they are off, or it is being unloaded. +#[derive(Debug)] +pub(super) struct Unavailable(pub String); + +impl std::fmt::Display for Unavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Unavailable {} + +pub(super) fn not_found(receipt_id: &str) -> anyhow::Error { + anyhow::Error::new(NotFound(format!("no receipt {receipt_id}"))) +} + +/// The reply a stage sends the stage before it for a request it did not +/// answer. +pub(super) fn reply(error: &anyhow::Error) -> ReceiptsReply { + if let Some(cannot) = error.downcast_ref::() + && let Ok(body) = serde_json::to_vec(cannot) + && body.len() <= MAX_STAGE_RECEIPTS_REFUSAL_BYTES + { + return ReceiptsReply::CannotOpen(body); + } + let mut reason = format!("{error:#}"); + let mut end = reason.len().min(MAX_STAGE_RECEIPTS_REFUSAL_BYTES); + while !reason.is_char_boundary(end) { + end -= 1; + } + reason.truncate(end); + if error.downcast_ref::().is_some() { + ReceiptsReply::NotFound(reason) + } else if error.downcast_ref::().is_some() { + ReceiptsReply::Unavailable(reason) + } else { + ReceiptsReply::Refused(reason) + } +} + +/// The answer in a later stage's reply, or the error that says why there +/// is none, as this stage would have raised it itself. +pub(super) fn answer(reply: ReceiptsReply) -> anyhow::Result> { + match reply { + ReceiptsReply::Answer(body) => Ok(body), + ReceiptsReply::Refused(reason) => anyhow::bail!("the next stage: {reason}"), + ReceiptsReply::NotFound(reason) => Err(anyhow::Error::new(NotFound(reason))), + ReceiptsReply::Unavailable(reason) => Err(anyhow::Error::new(Unavailable(reason))), + ReceiptsReply::CannotOpen(body) => match serde_json::from_slice::(&body) { + Ok(cannot) => Err(anyhow::Error::new(sanitized(cannot))), + Err(error) => { + anyhow::bail!( + "the next stage sent a cannot-open answer that does not parse: {error}" + ) + } + }, + } +} + +/// Bytes of a later stage's cannot-open detail that stage 0 passes on and +/// signs, at most: enough for any reason a stage gives. +pub(super) const MAX_LATER_DETAIL_BYTES: usize = 256; + +/// A later stage's cannot-open answer as stage 0 may sign it: its detail +/// cut to [`MAX_LATER_DETAIL_BYTES`], with no control characters, so a +/// stage cannot have stage 0 sign text that reads as more than a reason. +fn sanitized(mut cannot: CannotOpen) -> CannotOpen { + let mut detail: String = cannot + .detail + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let mut end = detail.len().min(MAX_LATER_DETAIL_BYTES); + while !detail.is_char_boundary(end) { + end -= 1; + } + detail.truncate(end); + cannot.detail = detail; + cannot +} + +/// `error` from the stages after stage `stage_index`, for a request of +/// `receipt_id`. A cannot-open answer for another receipt, or from a stage +/// that is not a later one, becomes a plain refusal, which no stage signs. +pub(super) fn from_later_stages( + error: anyhow::Error, + receipt_id: &str, + stage_index: u32, +) -> anyhow::Error { + match error.downcast_ref::() { + Some(cannot) if cannot.receipt_id != receipt_id || cannot.stage_index <= stage_index => { + anyhow::anyhow!( + "the next stage answered that stage {} cannot open another request", + cannot.stage_index + ) + } + _ => error, + } +} + +#[cfg(test)] +mod tests { + use skippy_receipts::wire::CannotOpenReason; + + use super::*; + + // Each reason survives the trip between two stages. + #[test] + fn a_reason_keeps_its_kind_between_stages() { + let cannot = CannotOpen { + receipt_id: "r".into(), + stage_index: 2, + reason: CannotOpenReason::CellsOverwritten, + detail: "a later request wrote the cell".into(), + }; + let error = answer(reply(&anyhow::Error::new(cannot.clone()))).unwrap_err(); + assert_eq!(error.downcast_ref::(), Some(&cannot)); + let error = answer(reply(¬_found("r"))).unwrap_err(); + assert!(error.downcast_ref::().is_some()); + let off = anyhow::Error::new(Unavailable("receipts are off".into())); + let error = answer(reply(&off)).unwrap_err(); + assert!(error.downcast_ref::().is_some()); + let refused = anyhow::anyhow!("x".repeat(2 * MAX_STAGE_RECEIPTS_REFUSAL_BYTES)); + let ReceiptsReply::Refused(reason) = reply(&refused) else { + panic!("a refusal"); + }; + assert_eq!(reason.len(), MAX_STAGE_RECEIPTS_REFUSAL_BYTES); + assert_eq!( + answer(ReceiptsReply::Answer(b"[]".to_vec())).unwrap(), + b"[]" + ); + } + + // A later stage cannot have stage 0 sign text of its choosing, or a + // cannot-open answer of another receipt or of an earlier stage. + #[test] + fn stage_zero_signs_only_a_later_stages_plain_reason() { + let cannot = |receipt_id: &str, stage_index: u32, detail: String| CannotOpen { + receipt_id: receipt_id.into(), + stage_index, + reason: CannotOpenReason::CellsOverwritten, + detail, + }; + let forged = cannot("r", 1, format!("ok\r\n{}", "x".repeat(4000))); + let body = serde_json::to_vec(&forged).unwrap(); + let error = answer(ReceiptsReply::CannotOpen(body)).unwrap_err(); + let passed = error.downcast_ref::().unwrap(); + assert_eq!(passed.detail.len(), MAX_LATER_DETAIL_BYTES); + assert!(passed.detail.starts_with("ok x")); + + for (receipt_id, stage_index) in [("other", 1), ("r", 0)] { + let error = anyhow::Error::new(cannot(receipt_id, stage_index, String::new())); + let error = from_later_stages(error, "r", 0); + assert!(error.downcast_ref::().is_none()); + } + let error = from_later_stages(anyhow::Error::new(cannot("r", 1, String::new())), "r", 0); + assert!(error.downcast_ref::().is_some()); + } +} diff --git a/crates/skippy-serving/src/receipts/reply_limits.rs b/crates/skippy-serving/src/receipts/reply_limits.rs new file mode 100644 index 00000000..c170556c --- /dev/null +++ b/crates/skippy-serving/src/receipts/reply_limits.rs @@ -0,0 +1,363 @@ +//! Bounds on what the stages after this one may answer, and the checks a +//! stage runs on their commitments before it keeps them. +//! +//! A stage reads no more of a later stage's reply than its own request can +//! produce. A commit produces one commitment per later stage. An opening +//! produces, per later stage, the boundary leaves of the picked positions, +//! the leaves of the picks in that stage's layers, the head residuals on +//! the last stage, the partials of its attention picks, the leaf hashes of +//! the picked positions of a cached prefix, and on a stage with hybrid +//! memory one recurrent region; rows produce the stored rows of +//! the picked blocks. The widths are the model's residual width, which +//! every stage of a chain shares, times a generous count of values, since +//! a stage does not know a later stage's matmul shapes. The bound is +//! twice the sum, and never above the protocol's own. + +use std::ops::Range; + +use anyhow::{Result, bail}; +use skippy_protocol::binary::MAX_STAGE_RECEIPTS_REPLY_BYTES; +use skippy_receipts::attention::opening::BlockChallenge; +use skippy_receipts::attention::{BLOCK_POSITIONS, blocks}; +use skippy_receipts::challenge::PREFIX_POSITIONS; +use skippy_receipts::commitment::slots_per_position; +use skippy_receipts::wire::{Challenge, StageCommitment}; + +use super::kept_turns::LaterStages; + +/// Stages a chain may have after any one stage. +pub(super) const LATER_STAGES: usize = 64; +/// A residual width for a stage that could not read its own. +const DEFAULT_WIDTH: usize = 16_384; +/// A hex hash as JSON, quoted, with its comma. +const HASH_BYTES: usize = 67; +/// A Merkle path as JSON: at most 64 hex hashes, quoted. +const PATH_BYTES: usize = 64 * HASH_BYTES; +/// Rows of the residual width an opened leaf may hold: both residuals, its +/// token-mixing values, and the inputs and outputs of its weight matmuls, +/// which may be several widths wide. +const LEAF_ROWS: usize = 2 + 32 + 64 * 16; +/// Rows of the residual width a mixing leaf of a recurrent region may hold. +const MIXING_LEAF_ROWS: usize = 32; +/// Stored rows of a layer at one position, each at most one width. +const STORED_ROWS: usize = 8; +/// The logits of one head position, base64: a vocabulary of 780,000. +const LOGITS_BYTES: usize = 4 << 20; +/// The recurrent states a region opens: the one its ubatch read and the +/// one it left. +const REGION_STATES_BYTES: usize = 64 << 20; +/// Fields and punctuation around the values of one JSON object. +const OBJECT_BYTES: usize = 1024; + +#[derive(Clone, Copy, Debug)] +pub(super) struct ReplyLimits { + /// Bytes of one residual row, base64. + row: usize, + /// The residual width, in values. + width: usize, +} + +fn base64_len(bytes: usize) -> usize { + bytes.div_ceil(3) * 4 +} + +impl ReplyLimits { + /// Limits for a model whose residual stream is `width` values wide; + /// `None` when the stage could not read it. + pub(super) fn for_width(width: Option) -> Self { + let width = width.filter(|&w| w > 0).unwrap_or(DEFAULT_WIDTH); + Self { + row: base64_len(width * size_of::()), + width, + } + } + + /// Bytes the commitments of the later stages may take for a turn of + /// `positions` positions: per stage its root, backend, cache types and + /// prefix, and the first position of each of its ubatches. + pub(super) fn commit(positions: u32) -> usize { + let stage = 2 * OBJECT_BYTES + 11 * positions as usize; + (LATER_STAGES * stage).min(MAX_STAGE_RECEIPTS_REPLY_BYTES) + } + + fn leaf(&self) -> usize { + LEAF_ROWS * self.row + 3 * PATH_BYTES + 8 * OBJECT_BYTES + } + + /// Bytes the later stages may answer `challenge` with. + pub(super) fn opening(&self, challenge: &Challenge, later: &LaterStages) -> usize { + let positions = challenge.positions().len(); + let boundary = PATH_BYTES + OBJECT_BYTES; + let last = later.commitments.len().saturating_sub(1); + let mut total = OBJECT_BYTES; + for (index, stage) in later.commitments.iter().enumerate() { + let layers = stage.layer_start..stage.layer_end; + let leaves: usize = challenge + .picks + .iter() + .filter(|pick| layers.contains(&pick.layer)) + .map(|pick| pick.positions.len()) + .sum(); + let attention = challenge + .attention + .iter() + .filter(|pick| layers.contains(&pick.layer)) + .count(); + total += OBJECT_BYTES + positions * 2 * boundary + leaves * self.leaf(); + // a picked position of a cached prefix: a hash per leaf of the + // stage and per stored leaf of its layers, and its path + let hashes = slots_per_position(stage.layer_start, stage.layer_end) as usize + + (stage.layer_end - stage.layer_start) as usize; + total += PREFIX_POSITIONS * (hashes * HASH_BYTES + PATH_BYTES + OBJECT_BYTES); + if index == last { + let head = self.row + LOGITS_BYTES + PATH_BYTES + OBJECT_BYTES; + total += challenge.head.len() * head; + } + // one head's partials: per block of attended positions, a + // logit, a sum and a value row + let partials = blocks(later.position_end as usize) + * base64_len((2 + self.width) * size_of::()); + total += attention * (partials + OBJECT_BYTES); + if attention > 0 && stage.recurrent_state.is_some() { + total += self.region(stage, later.position_end); + } + } + total.saturating_mul(2).min(MAX_STAGE_RECEIPTS_REPLY_BYTES) + } + + /// Bytes a recurrent region of `stage` may take: a mixing leaf per + /// position of its largest ubatch and one more, and two states. + fn region(&self, stage: &StageCommitment, position_end: u32) -> usize { + let ends = stage.ubatches.iter().skip(1).copied().chain([position_end]); + let largest = stage + .ubatches + .iter() + .zip(ends) + .map(|(&start, end)| end.saturating_sub(start)) + .max() + .unwrap_or(0) as usize; + let leaf = MIXING_LEAF_ROWS * self.row + PATH_BYTES + OBJECT_BYTES; + (largest + 1) * leaf + REGION_STATES_BYTES + } + + /// Bytes the later stages may answer `blocks` with: the stored rows of + /// every position of every picked block, each with its proof. + pub(super) fn rows(&self, blocks: &BlockChallenge) -> usize { + let row = STORED_ROWS * self.row + 2 * PATH_BYTES + OBJECT_BYTES; + let positions: usize = blocks + .picks + .iter() + .map(|pick| pick.blocks.len() * BLOCK_POSITIONS) + .sum(); + (LATER_STAGES * OBJECT_BYTES + positions * row) + .saturating_mul(2) + .min(MAX_STAGE_RECEIPTS_REPLY_BYTES) + } +} + +/// Refuses the commitments of the stages after `own` unless they continue +/// the plan: stage after stage, each holding the layers that follow the +/// previous stage's, with the leaves its layers make over `positions`, and +/// with fields no longer than a commitment's. +pub(super) fn check_commitments( + own: &StageCommitment, + later: &[StageCommitment], + positions: &Range, +) -> Result<()> { + if later.is_empty() { + bail!("the next stage committed nothing"); + } + if later.len() > LATER_STAGES { + bail!("the next stage answered for {} stages", later.len()); + } + let span = u64::from(positions.end - positions.start); + let mut previous = own; + for stage in later { + if stage.stage_index != previous.stage_index + 1 + || stage.layer_start != previous.layer_end + || stage.layer_end <= stage.layer_start + { + bail!( + "stage {} commits layers {}..{}, after stage {} with layers {}..{}", + stage.stage_index, + stage.layer_start, + stage.layer_end, + previous.stage_index, + previous.layer_start, + previous.layer_end + ); + } + let leaves = span * slots_per_position(stage.layer_start, stage.layer_end); + if stage.leaf_count != leaves { + bail!( + "stage {} commits {} leaves; its layers make {leaves} over positions {positions:?}", + stage.stage_index, + stage.leaf_count + ); + } + let hex = |text: &str| text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit()); + let fields = hex(&stage.root) + && stage.backend.len() <= 256 + && stage.cache_types.len() <= 16 + && stage.cache_types.iter().all(|t| t.len() <= 32) + && stage.ubatches.len() as u64 <= span + // a later stage holds no layer 0, so it commits no tokens + && stage + .prefix + .as_ref() + .is_none_or(|p| hex(&p.root) && p.tokens.is_none()) + && stage.recurrent_state.as_deref().is_none_or(hex); + if !fields { + bail!("stage {} sent a malformed commitment", stage.stage_index); + } + previous = stage; + } + Ok(()) +} + +/// Refuses an opening or rows of the later stages unless one part came +/// from each stage that committed the turn, in order. +pub(super) fn check_stages(later: &LaterStages, answered: impl Iterator) -> Result<()> { + let committed = later.commitments.iter().map(|stage| stage.stage_index); + if !committed.eq(answered) { + bail!("the next stage did not answer for the stages that committed the turn, in order"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use skippy_receipts::attention::opening::{AttentionPick, BlockPick}; + use skippy_receipts::wire::Pick; + + use super::*; + + fn commitment(index: u32, layers: Range, positions: u32) -> StageCommitment { + StageCommitment { + stage_index: index, + layer_start: layers.start, + layer_end: layers.end, + root: "ab".repeat(32), + leaf_count: u64::from(positions) * slots_per_position(layers.start, layers.end), + backend: "test".into(), + cache_types: vec!["f16".into()], + prefix: None, + ubatches: vec![0], + recurrent_state: None, + } + } + + fn later(commitments: Vec) -> LaterStages { + LaterStages { + position_start: 0, + position_end: 8, + commitments: commitments.into(), + } + } + + fn challenge(layers: &[u32]) -> Challenge { + Challenge { + receipt_id: "r".into(), + picks: layers + .iter() + .map(|&layer| Pick { + layer, + positions: vec![1, 2], + }) + .collect(), + proof: None, + head: Vec::new(), + attention: Vec::new(), + } + } + + // A later stage's commitment is kept only when it continues the plan. + #[test] + fn a_commitment_must_continue_the_plan() { + let own = commitment(0, 0..2, 8); + let next = commitment(1, 2..4, 8); + let last = commitment(2, 4..6, 8); + check_commitments(&own, &[next.clone(), last.clone()], &(0..8)).unwrap(); + type Change = fn(&mut StageCommitment); + let changes: [Change; 9] = [ + // a later stage holds no layer 0: the prefix's tokens are not its + |s| { + s.prefix = Some(skippy_receipts::wire::PrefixCommitment { + root: "ab".repeat(32), + positions: 8, + tokens: Some("ab".repeat(32)), + }); + }, + |s| s.stage_index = 3, + |s| s.layer_start = 3, + |s| s.layer_end = 2, + |s| s.leaf_count += 1, + |s| s.root = "zz".repeat(32), + |s| s.backend = "b".repeat(1000), + |s| s.ubatches = vec![0; 9], + |s| s.recurrent_state = Some("short".into()), + ]; + for (i, change) in changes.iter().enumerate() { + let mut forged = next.clone(); + change(&mut forged); + let result = check_commitments(&own, &[forged, last.clone()], &(0..8)); + assert!(result.is_err(), "change {i} was kept"); + } + assert!(check_commitments(&own, &[], &(0..8)).is_err()); + assert!(check_commitments(&own, &[last], &(0..8)).is_err(), "a gap"); + // the leaves are those of the turn's positions + assert!(check_commitments(&own, &[next], &(0..9)).is_err()); + } + + // What a later stage may answer follows from what the challenge asks + // of it. + #[test] + fn a_reply_is_bounded_by_what_its_request_asks() { + let limits = ReplyLimits::for_width(Some(8)); + let stages = later(vec![commitment(1, 2..4, 8), commitment(2, 4..6, 8)]); + let none = limits.opening(&challenge(&[0, 1]), &stages); + let one = limits.opening(&challenge(&[0, 3]), &stages); + let two = limits.opening(&challenge(&[3, 5]), &stages); + assert!(none < one && one < two, "{none} {one} {two}"); + assert!(none < 256 << 10, "boundary leaves alone: {none}"); + let mut heads = challenge(&[0]); + heads.head = vec![1, 2]; + assert!(limits.opening(&heads, &stages) > none + 2 * LOGITS_BYTES); + let mut attention = challenge(&[3]); + attention.attention = vec![AttentionPick { + position: 1, + layer: 3, + head_draw: 0, + }]; + assert!(limits.opening(&attention, &stages) > one); + // a wider model may answer more, up to the protocol's bound + let wide = ReplyLimits::for_width(Some(1 << 20)); + assert!(wide.opening(&challenge(&[3]), &stages) > one); + assert_eq!( + wide.opening(&challenge(&[3, 5]), &stages), + MAX_STAGE_RECEIPTS_REPLY_BYTES + ); + + let blocks = |n: u32| BlockChallenge { + receipt_id: "r".into(), + picks: vec![BlockPick { + position: 1, + layer: 3, + blocks: (0..n).collect(), + }], + proof: None, + }; + assert!(limits.rows(&blocks(0)) < limits.rows(&blocks(2))); + assert!(ReplyLimits::commit(8) < ReplyLimits::commit(8000)); + assert!(ReplyLimits::commit(8) < 1 << 20); + } + + #[test] + fn an_answer_must_come_from_the_stages_that_committed() { + let stages = later(vec![commitment(1, 2..4, 8), commitment(2, 4..6, 8)]); + check_stages(&stages, [1, 2].into_iter()).unwrap(); + for answered in [vec![1], vec![2, 1], vec![1, 2, 3], vec![0, 1, 2]] { + assert!(check_stages(&stages, answered.into_iter()).is_err()); + } + } +} diff --git a/crates/skippy-serving/src/receipts/report_queue.rs b/crates/skippy-serving/src/receipts/report_queue.rs new file mode 100644 index 00000000..32877acd --- /dev/null +++ b/crates/skippy-serving/src/receipts/report_queue.rs @@ -0,0 +1,244 @@ +//! Applies the native recorder's reports to the stage's [`Recorder`] on a +//! worker thread, in the order they were made. +//! +//! The decoding thread only queues a report, so hashing a ubatch's leaves +//! overlaps the GPU computing the next one. The runtime holds the next +//! ubatch until the worker drops the previous one, which bounds the queue. +//! Reads of the recorder (commit, open, recorded range) first flush the +//! native recorder, which on an asynchronous device holds the last ubatches +//! back, and then wait until every report queued before +//! them has been applied. +//! +//! The start of a session's turn is a report like the others, so the +//! recorder sees it between the ubatches computed before the session took +//! its sequence and the session's own. + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::mpsc::{self, Sender}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; +use std::thread::JoinHandle; + +use skippy_receipts::recorder::{MemoryOp, Recorder, TurnId}; +use skippy_runtime::{ReceiptFlusher, ReceiptMemoryEvent, RecordedUbatch}; + +use super::native::apply_ubatch; + +pub(super) enum Report { + Ubatch(RecordedUbatch), + Unreceiptable(String), + /// A ubatch the native recorder could not receipt. + UnrecordedUbatch(String), + Memory(ReceiptMemoryEvent), + /// The recurrent state the next turn of `seq` starts from. + State { + seq: i32, + state: Option>, + }, + /// A session starts turn `turn` on `seq`. + Turn { + seq: i32, + turn: TurnId, + }, +} + +/// Reports queued and applied so far. +#[derive(Default)] +struct Progress { + counts: Mutex<(u64, u64)>, + applied: Condvar, +} + +impl Progress { + fn lock(&self) -> std::sync::MutexGuard<'_, (u64, u64)> { + self.counts.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +pub(super) struct ReportQueue { + recorder: Arc, + progress: Arc, + sender: Mutex>>, + worker: Mutex>>, + native: OnceLock, +} + +impl ReportQueue { + pub(super) fn new(recorder: Arc) -> Self { + Self { + recorder, + progress: Arc::default(), + sender: Mutex::new(None), + worker: Mutex::new(None), + native: OnceLock::new(), + } + } + + /// The native recorder whose held-back ubatch a read reports first. + pub(super) fn set_native(&self, flusher: ReceiptFlusher) { + let _ = self.native.set(flusher); + } + + pub(super) fn recorder(&self) -> &Recorder { + &self.recorder + } + + /// The recorder, for a test's replayer to hold as the native one holds + /// its stage. + #[cfg(test)] + pub(super) fn shared_recorder(&self) -> Arc { + self.recorder.clone() + } + + /// Queues the start of a session's turn on `seq`, after every ubatch + /// computed before it: the ubatches the native recorder still holds + /// back are reported first. Call it with the stage idle, before the + /// session's first ubatch. On a stage with hybrid memory, that ubatch + /// then reports the recurrent state the turn starts from, also when the + /// sequence was not removed whole since its last turn. + pub(super) fn begin_turn(&self, seq: i32, turn: TurnId) { + self.flush_native(); + self.push(Report::Turn { seq, turn }); + self.arm_state(seq); + } + + fn flush_native(&self) { + if let Some(native) = self.native.get() + && let Err(error) = native.flush() + { + tracing::warn!("receipts: cannot flush the recorder: {error:#}"); + } + } + + /// Starts a new turn of `seq` in the native recorder, which on a stage + /// with hybrid memory reports the state the turn starts from. + pub(super) fn arm_state(&self, seq: i32) { + if let Some(native) = self.native.get() + && let Err(error) = native.arm_state(seq) + { + tracing::warn!("receipts: cannot mark the start of a turn: {error:#}"); + } + } + + /// Queues a report, starting the worker on first use. + pub(super) fn push(&self, report: Report) { + let mut sender = self.sender.lock().unwrap_or_else(PoisonError::into_inner); + let sender = sender.get_or_insert_with(|| self.spawn_worker()); + self.progress.lock().0 += 1; + if let Err(mpsc::SendError(report)) = sender.send(report) { + // the worker is gone; apply here so the counts still meet + apply(&self.recorder, report); + mark_applied(&self.progress); + } + } + + /// Waits until every report made before the call has been applied. + pub(super) fn wait_applied(&self) { + self.flush_native(); + let counts = self.progress.lock(); + let target = counts.0; + drop( + self.progress + .applied + .wait_while(counts, |counts| counts.1 < target) + .unwrap_or_else(PoisonError::into_inner), + ); + } + + fn spawn_worker(&self) -> Sender { + let (sender, receiver) = mpsc::channel::(); + let recorder = self.recorder.clone(); + let progress = self.progress.clone(); + let spawned = std::thread::Builder::new() + .name("receipt-recorder".into()) + .spawn(move || { + for report in receiver { + apply(&recorder, report); + mark_applied(&progress); + } + }); + match spawned { + Ok(worker) => { + *self.worker.lock().unwrap_or_else(PoisonError::into_inner) = Some(worker); + } + // dropping the receiver makes every send fail, so push applies inline + Err(error) => tracing::warn!("receipts: cannot start the recorder thread: {error}"), + } + sender + } +} + +impl Drop for ReportQueue { + /// Ends the worker, so the recorder it holds goes with the queue. + fn drop(&mut self) { + let sender = self + .sender + .get_mut() + .unwrap_or_else(PoisonError::into_inner) + .take(); + drop(sender); + let worker = self + .worker + .get_mut() + .unwrap_or_else(PoisonError::into_inner) + .take(); + if let Some(worker) = worker { + let _ = worker.join(); + } + } +} + +fn mark_applied(progress: &Progress) { + progress.lock().1 += 1; + progress.applied.notify_all(); +} + +fn apply(recorder: &Recorder, report: Report) { + let applied = catch_unwind(AssertUnwindSafe(|| match report { + Report::Ubatch(ubatch) => apply_ubatch(recorder, ubatch), + Report::Unreceiptable(reason) => { + tracing::warn!("receipts: the recorder lost track of the stage: {reason}"); + recorder.unreceiptable(&reason); + } + Report::UnrecordedUbatch(reason) => { + tracing::debug!("receipts: a ubatch cannot be receipted: {reason}"); + recorder.unrecorded_ubatch(&reason); + } + Report::Memory(event) => match MemoryOp::from_code(event.op) { + Some(op) => recorder.memory_op(op, event.seq, event.seq_dst, event.p0, event.p1), + None => recorder.unreceiptable(&format!("unknown KV-cache operation {}", event.op)), + }, + Report::State { seq, state } => recorder.record_state(seq, state.as_deref()), + Report::Turn { seq, turn } => recorder.begin_turn(seq, turn), + })); + if applied.is_err() { + recorder.unreceiptable("recording a report panicked"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waiting_sees_every_report_queued_before_it() { + let queue = ReportQueue::new(Arc::new(Recorder::new(0, 0..2, "test"))); + for i in 0..100 { + queue.push(Report::Unreceiptable(format!("report {i}"))); + } + queue.wait_applied(); + assert_eq!(*queue.progress.lock(), (100, 100)); + } + + // The worker holds the recorder; it ends with the queue, so a stage + // that is dropped leaves no recorder behind. + #[test] + fn the_recorder_goes_with_the_queue() { + let recorder = Arc::new(Recorder::new(0, 0..2, "test")); + let weak = Arc::downgrade(&recorder); + let queue = ReportQueue::new(recorder); + queue.begin_turn(1, TurnId(4)); + queue.wait_applied(); + drop(queue); + assert!(weak.upgrade().is_none()); + } +} diff --git a/crates/skippy-serving/src/receipts/sampler_statement.rs b/crates/skippy-serving/src/receipts/sampler_statement.rs new file mode 100644 index 00000000..eda61d81 --- /dev/null +++ b/crates/skippy-serving/src/receipts/sampler_statement.rs @@ -0,0 +1,613 @@ +//! How a turn chose its tokens, as its receipt states it. +//! +//! The statement goes into the signed turn root, so a node that samples +//! otherwise than it says signs a false statement, and a client checks a +//! turn that says it decoded greedily against the output head. + +use skippy_receipts::turn; + +/// The grammar a turn's chat metadata constrains it with, if any. +fn grammar(chat_metadata: Option<&str>) -> Option { + let metadata: serde_json::Value = serde_json::from_str(chat_metadata?).ok()?; + let grammar = metadata.get("grammar")?.as_str()?; + (!grammar.is_empty()).then(|| grammar.to_owned()) +} + +/// What the runtime builds a turn's reasoning-budget sampler from, as the +/// chat metadata gives it: the tag that starts the reasoning, the tags +/// that end it, and the text the chat template placed after the prompt, +/// which the sampler reads first. `None` when the runtime builds no such +/// sampler: the turn has no budget, or the metadata the runtime configures +/// the sampler with names no tags (`chat_params` in the patch's +/// `src/skippy/sampling_config.cpp`). The runtime does not configure a +/// turn without a grammar with its whole metadata +/// (`skippy_runtime::chat_sampling_metadata_for_native`): it gives the +/// reasoning tags only when the turn has a finite budget and the template +/// did not already close the reasoning block. So the statement reads the +/// metadata through that function, and a turn that the runtime gave no +/// tags states no reasoning-budget sampler, whatever budget it states. +/// +/// A client replays the sampler from these to know which tokens it forced +/// (`skippy_receipts::head::reasoning_budget`), so they are the texts the +/// runtime was given, unchanged. A statement that named a sampler the +/// runtime did not build would fail an honest turn whose reasoning runs +/// past the budget. +fn reasoning_sampler( + sampling: &skippy_runtime::SamplingConfig, + chat_metadata: Option<&str>, +) -> Option { + let budget = reasoning_budget_tokens(sampling.reasoning_budget)?; + // the runtime passes the budget as an i32, and so does this + let budget = i32::try_from(budget).unwrap_or(i32::MAX); + let given = skippy_runtime::chat_sampling_metadata_for_native(chat_metadata?, Some(budget)); + let metadata: serde_json::Value = serde_json::from_str(&given).ok()?; + let start = metadata.get("thinking_start_tag")?.as_str()?; + let ends: Vec<&str> = metadata + .get("thinking_end_tags")? + .as_array()? + .iter() + .filter_map(serde_json::Value::as_str) + .filter(|end| !end.is_empty()) + .collect(); + if start.is_empty() || ends.is_empty() { + return None; + } + let prefill = metadata + .get("generation_prompt") + .and_then(serde_json::Value::as_str) + .unwrap_or_default(); + Some(serde_json::json!({ "start": start, "ends": ends, "prefill": prefill })) +} + +/// Whether the runtime replaces the turn's chain by a temperature of 0, which +/// keeps the best logit: sampling is off, or nothing but a temperature of 0 +/// shapes the choice. This is `skippy_sampling_is_greedy_equivalent` of the +/// patch's `src/skippy/sampling.cpp`, which `sampling_params` of +/// `src/skippy/sampling_config.cpp` reads; a turn that ignores its end is not +/// one, since the runtime takes the end tokens out of its candidates. +fn runs_greedy_chain(sampling: &skippy_runtime::SamplingConfig) -> bool { + let repeat = if sampling.repeat_penalty == 0.0 { + 1.0 + } else { + sampling.repeat_penalty + }; + !sampling.enabled + || (sampling.temperature <= 0.0 + && !sampling.ignore_eos + && sampling.presence_penalty == 0.0 + && sampling.frequency_penalty == 0.0 + && repeat == 1.0 + && sampling.logit_bias.is_empty()) +} + +/// Whether a turn took the best logit at every token: no temperature, +/// penalty, logit bias, ignored end or grammar changed the choice. The +/// receipt says so, and a client checks greedy turns against the output +/// head. +pub(crate) fn greedy_sampling( + sampling: &skippy_runtime::SamplingConfig, + chat_metadata: Option<&str>, +) -> bool { + let unconstrained = grammar(chat_metadata).is_none(); + unconstrained + && runs_greedy_chain(sampling) + && reasoning_budget_tokens(sampling.reasoning_budget).is_none() +} + +/// The runtime's default chain, which it runs when a request names none +/// (`sampling_params` of `src/skippy/sampling_config.cpp`): typical-p and +/// top-p only when they are between 0 and 1. +fn default_chain(sampling: &skippy_runtime::SamplingConfig) -> Vec { + let between = |p: f32| p > 0.0 && p < 1.0; + [ + "penalties", + "dry", + "top_n_sigma", + "top_k", + "typical_p", + "top_p", + "min_p", + "xtc", + "temperature", + ] + .into_iter() + .filter(|name| match *name { + "typical_p" => between(sampling.typical_p), + "top_p" => between(sampling.top_p), + _ => true, + }) + .map(str::to_owned) + .collect() +} + +/// The chain the runtime runs for the turn: the request's, or its default +/// one. +fn chain_run(sampling: &skippy_runtime::SamplingConfig) -> Vec { + if sampling.samplers.is_empty() { + default_chain(sampling) + } else { + sampling.samplers.clone() + } +} + +/// Whether a turn's last sampler is the stream draw that the indexed draw +/// replaces: the turn does not take the best logit, and mirostat, which picks +/// its token itself, is off. +pub(crate) fn draws_from_the_chain( + sampling: &skippy_runtime::SamplingConfig, + chat_metadata: Option<&str>, +) -> bool { + !greedy_sampling(sampling, chat_metadata) && sampling.mirostat_mode == 0 +} + +/// Whether the last sampler of the turn's chain draws at random, as +/// `common_sampler_init` of `common/sampling.cpp` decides: it takes the best +/// logit after a chain that ends in a temperature of 0 that is not dynamic, +/// or in a top-k of 1, and draws after any other. A chain the runtime +/// replaced by a temperature of 0 ([`runs_greedy_chain`]) takes the best +/// logit, also in a turn that is not greedy because a reasoning budget or a +/// grammar constrains it. The runtime installs no indexed draw on a chain +/// that does not draw, so the statement names none. +fn last_sampler_draws(sampling: &skippy_runtime::SamplingConfig) -> bool { + if runs_greedy_chain(sampling) { + return false; + } + match chain_run(sampling).last().map(String::as_str) { + Some("temperature") => sampling.temperature > 0.0 || sampling.dynatemp_range > 0.0, + Some("top_k") => sampling.top_k != 1, + _ => true, + } +} + +/// Makes the draw of a sampled turn one a client can replay: the indexed +/// draw, with the seed the receipt will state. A request that set no seed +/// takes `client_seed`, the one its receipt request named, else a random +/// one, so the node never states a seed it did not use. +/// A turn with a receipt request draws with the seed the request names: the +/// seed of its body, else the one of its receipt request (`x-receipt-seed`), +/// else an operator's default. `body_seed` is the body's, before the +/// defaults filled it in. A client that set the receipt seed is held to the +/// token that seed picks, so a default must not override it. +pub(crate) fn prefer_receipt_seed( + mut sampling: skippy_runtime::SamplingConfig, + body_seed: Option, + receipt_seed: Option, +) -> skippy_runtime::SamplingConfig { + let asked = receipt_seed.filter(|seed| *seed != 0); + // a seed of 0 is none: the draw takes the receipt seed later + if let (None, Some(seed), true) = (body_seed, asked, sampling.seed != 0) { + sampling.seed = seed; + } + sampling +} + +pub(crate) fn make_draw_replayable( + sampling: &mut skippy_runtime::SamplingConfig, + chat_metadata: Option<&str>, + client_seed: Option, +) { + if !draws_from_the_chain(sampling, chat_metadata) { + return; + } + sampling.indexed_draw = last_sampler_draws(sampling); + if sampling.seed == 0 { + sampling.seed = client_seed + .filter(|seed| *seed != 0) + .unwrap_or_else(|| rand::RngExt::random_range(&mut rand::rng(), 1..=u32::MAX)); + } +} + +/// How a turn chose its tokens, as its receipt states it: [`turn::GREEDY`] +/// when it took the best logit at every token, else the sampler's +/// parameters and seed, so a node that samples otherwise than it says signs +/// a false statement. A grammar is named by its BLAKE3 hash. +/// `draw` names the rule the last sampler drew by when a client can replay +/// it ([`turn::INDEXED_DRAW`]), and [`turn::REASONING`] what the turn's +/// reasoning-budget sampler was built from ([`reasoning_sampler`]). +pub(crate) fn sampler_statement( + sampling: &skippy_runtime::SamplingConfig, + chat_metadata: Option<&str>, +) -> String { + if greedy_sampling(sampling, chat_metadata) { + return turn::GREEDY.to_owned(); + } + let grammar = + grammar(chat_metadata).map(|grammar| blake3::hash(grammar.as_bytes()).to_hex().to_string()); + let s = sampling; + turn::sampled(&serde_json::json!({ + "seed": s.seed, + "draw": s.indexed_draw.then_some(turn::INDEXED_DRAW), + // what the runtime ran: its default chain for a request that named + // none, and a temperature of 0 where sampling is off + "samplers": chain_run(s), + "temperature": if s.enabled { s.temperature } else { 0.0 }, + "dynatemp_range": s.dynatemp_range, + "dynatemp_exponent": s.dynatemp_exponent, + "top_k": s.top_k, + "top_p": s.top_p, + "min_p": s.min_p, + "typical_p": s.typical_p, + "top_nsigma": s.top_nsigma, + "presence_penalty": s.presence_penalty, + "frequency_penalty": s.frequency_penalty, + "repeat_penalty": s.repeat_penalty, + "penalty_last_n": s.penalty_last_n, + "dry": { + "multiplier": s.dry.multiplier, + "base": s.dry.base, + "allowed_length": s.dry.allowed_length, + "penalty_last_n": s.dry.penalty_last_n, + "sequence_breakers": s.dry.sequence_breakers, + }, + "xtc": { "probability": s.xtc.probability, "threshold": s.xtc.threshold }, + "mirostat": { + "mode": s.mirostat_mode, + "entropy": s.mirostat_entropy, + "learning_rate": s.mirostat_learning_rate, + }, + "logit_bias": s.logit_bias.iter().map(|b| (b.token_id, b.bias)).collect::>(), + "ignore_eos": s.ignore_eos, + "grammar": grammar, + "reasoning_budget": reasoning_budget_tokens(s.reasoning_budget), + (turn::REASONING): reasoning_sampler(s, chat_metadata), + })) +} + +/// The tokens a reasoning budget allows, `None` when it is unrestricted. A +/// budget can force the end of reasoning, so it is part of the statement. +fn reasoning_budget_tokens(budget: skippy_runtime::ReasoningBudget) -> Option { + use skippy_runtime::ReasoningBudget; + match budget { + ReasoningBudget::Unrestricted => None, + ReasoningBudget::Explicit(tokens) | ReasoningBudget::Capped(tokens) => { + Some(i64::from(tokens)) + } + ReasoningBudget::Resolved(tokens) => (tokens >= 0).then_some(i64::from(tokens)), + } +} + +#[cfg(test)] +mod tests { + use skippy_runtime::{LogitBias, SamplingConfig}; + + use super::*; + + #[test] + fn only_a_turn_that_takes_the_best_logit_is_greedy() { + let disabled = SamplingConfig::default(); + assert!(greedy_sampling(&disabled, None)); + let mut zero = SamplingConfig { + enabled: true, + temperature: 0.0, + ..SamplingConfig::default() + }; + assert!(greedy_sampling(&zero, Some(r#"{"grammar":""}"#))); + assert!(!greedy_sampling( + &zero, + Some(r#"{"grammar":"root ::= \"a\""}"#) + )); + zero.logit_bias.push(LogitBias { + token_id: 5, + bias: 1.0, + }); + assert!(!greedy_sampling(&zero, None)); + let warm = SamplingConfig { + enabled: true, + temperature: 0.7, + ..SamplingConfig::default() + }; + assert!(!greedy_sampling(&warm, None)); + } + + #[test] + fn a_sampled_turn_states_its_parameters_and_seed() { + assert_eq!( + sampler_statement(&SamplingConfig::default(), None), + turn::GREEDY + ); + let warm = SamplingConfig { + enabled: true, + temperature: 0.7, + seed: 1234, + ..SamplingConfig::default() + }; + let grammar = Some(r#"{"grammar":"root ::= \"a\""}"#); + let statement = sampler_statement(&warm, grammar); + let parameters = turn::sampler_parameters(&statement).expect("parameters"); + assert_eq!(parameters["seed"], 1234); + assert!((parameters["temperature"].as_f64().unwrap() - 0.7).abs() < 1e-6); + assert_eq!(parameters["grammar"].as_str().map(str::len), Some(64)); + let other = SamplingConfig { seed: 99, ..warm }; + assert_ne!(sampler_statement(&other, grammar), statement); + } + + fn warm() -> SamplingConfig { + SamplingConfig { + enabled: true, + temperature: 0.7, + ..SamplingConfig::default() + } + } + + #[test] + fn a_sampled_turn_with_a_receipt_draws_by_the_indexed_draw() { + // the request set a seed: it is the one stated and used + let mut seeded = SamplingConfig { + seed: 1234, + ..warm() + }; + make_draw_replayable(&mut seeded, None, Some(99)); + assert!(seeded.indexed_draw); + assert_eq!(seeded.seed, 1234); + let parameters = turn::sampler_parameters(&sampler_statement(&seeded, None)).unwrap(); + assert_eq!(parameters["draw"], turn::INDEXED_DRAW); + assert_eq!(parameters["seed"], 1234); + // no seed in the request: the receipt request's seed + let mut asked = warm(); + make_draw_replayable(&mut asked, None, Some(99)); + assert_eq!((asked.indexed_draw, asked.seed), (true, 99)); + // none there either, or 0: a random one above 0, which is stated + for client_seed in [None, Some(0)] { + let mut unseeded = warm(); + make_draw_replayable(&mut unseeded, None, client_seed); + assert!(unseeded.indexed_draw); + assert_ne!(unseeded.seed, 0); + let parameters = turn::sampler_parameters(&sampler_statement(&unseeded, None)).unwrap(); + assert_eq!(parameters["seed"], unseeded.seed); + } + } + + #[test] + fn a_turn_that_takes_the_best_logit_under_a_budget_states_no_draw() { + // a request that turns every filter off at a temperature of 1 is + // decoded greedily; a reasoning budget makes its statement a + // sampled one, which must not name a draw the chain never made + let disabled = SamplingConfig { + enabled: false, + temperature: 1.0, + ..budgeted(16) + }; + let cold = SamplingConfig { + temperature: 0.0, + ..budgeted(16) + }; + for mut best in [disabled, cold] { + make_draw_replayable(&mut best, None, Some(99)); + assert!(!best.indexed_draw); + // the receipt request's seed is still the one stated + assert_eq!(best.seed, 99); + let parameters = turn::sampler_parameters(&sampler_statement(&best, None)).unwrap(); + assert!(parameters["draw"].is_null(), "{parameters}"); + assert_eq!(parameters["reasoning_budget"], 16); + } + // a budgeted turn that samples does name it + let mut warm = SamplingConfig { + temperature: 0.7, + ..budgeted(16) + }; + make_draw_replayable(&mut warm, None, Some(99)); + assert!(warm.indexed_draw); + } + + #[test] + fn a_turn_that_does_not_draw_from_the_chain_is_left_alone() { + // a greedy turn has no draw + let mut greedy = SamplingConfig::default(); + make_draw_replayable(&mut greedy, None, Some(99)); + assert_eq!(greedy, SamplingConfig::default()); + // mirostat picks its token itself + let mut mirostat = SamplingConfig { + mirostat_mode: 2, + ..warm() + }; + make_draw_replayable(&mut mirostat, None, Some(99)); + assert!(!mirostat.indexed_draw); + assert_eq!(mirostat.seed, 0); + // a turn without a receipt states no draw + let parameters = turn::sampler_parameters(&sampler_statement(&warm(), None)).unwrap(); + assert!(parameters["draw"].is_null()); + } + + // The runtime configures the sampler of a turn with a grammar from the + // whole metadata, and so builds its reasoning-budget sampler. + const THINKING: &str = r#"{"grammar":"root ::= \"a\"","generation_prompt":"<|im_start|>assistant\n","thinking_start_tag":"","thinking_end_tags":["","",7],"supports_thinking":true}"#; + + fn budgeted(tokens: i32) -> SamplingConfig { + SamplingConfig { + reasoning_budget: skippy_runtime::ReasoningBudget::Resolved(tokens), + ..warm() + } + } + + #[test] + fn a_turn_with_a_reasoning_budget_states_what_its_sampler_was_built_from() { + let statement = sampler_statement(&budgeted(256), Some(THINKING)); + let parameters = turn::sampler_parameters(&statement).unwrap(); + assert_eq!(parameters["reasoning_budget"], 256); + // the tags as the runtime reads them: an end tag that is no text, + // or empty, builds nothing + assert_eq!( + parameters[turn::REASONING], + serde_json::json!({ + "start": "", + "ends": [""], + "prefill": "<|im_start|>assistant\n", + }) + ); + // a greedy request with a budget is a sampled statement too + let greedy = SamplingConfig { + temperature: 0.0, + ..budgeted(0) + }; + let parameters = + turn::sampler_parameters(&sampler_statement(&greedy, Some(THINKING))).unwrap(); + assert_eq!(parameters[turn::REASONING]["start"], ""); + } + + #[test] + fn a_turn_whose_runtime_builds_no_reasoning_sampler_states_none() { + let stated = |sampling: &SamplingConfig, metadata: Option<&str>| { + turn::sampler_parameters(&sampler_statement(sampling, metadata)).unwrap() + [turn::REASONING] + .clone() + }; + // no budget + assert!(stated(&budgeted(-1), Some(THINKING)).is_null()); + assert!(stated(&warm(), Some(THINKING)).is_null()); + // a budget, and metadata that names no tags, or no metadata + assert!(stated(&budgeted(64), Some(r#"{"grammar":""}"#)).is_null()); + assert!(stated(&budgeted(64), None).is_null()); + let no_start = r#"{"thinking_start_tag":"","thinking_end_tags":[""]}"#; + assert!(stated(&budgeted(64), Some(no_start)).is_null()); + let no_end = r#"{"thinking_start_tag":"","thinking_end_tags":[""]}"#; + assert!(stated(&budgeted(64), Some(no_end)).is_null()); + } + + #[test] + fn a_turn_without_a_grammar_states_the_reasoning_sampler_the_runtime_builds() { + // The statement follows what the runtime gives native sampling. A + // statement that named a sampler the runtime did not build made a + // client expect the end tag where the budget ran out, and fail an + // honest turn that reasoned on. One that left out a sampler the + // runtime did build would fail the honest turn it cut short. + let open = r#"{"grammar":"","generation_prompt":"<|im_start|>assistant\n","thinking_start_tag":"","thinking_end_tags":[""],"supports_thinking":true}"#; + let given = skippy_runtime::chat_sampling_metadata_for_native(open, Some(16)); + assert!(given.contains("thinking_start_tag"), "{given}"); + let parameters = + turn::sampler_parameters(&sampler_statement(&budgeted(16), Some(open))).unwrap(); + assert_eq!( + parameters[turn::REASONING], + serde_json::json!({ + "start": "", + "ends": [""], + "prefill": "<|im_start|>assistant\n", + }) + ); + assert_eq!(parameters["reasoning_budget"], 16); + + // the template closed the reasoning block: the runtime builds no + // budget sampler, and the statement names none + let closed = r#"{"grammar":"","generation_prompt":"<|im_start|>assistant\n\n\n\n\n","thinking_start_tag":"","thinking_end_tags":[""],"supports_thinking":true}"#; + assert_eq!( + skippy_runtime::chat_sampling_metadata_for_native(closed, Some(16)), + r#"{"grammar":""}"# + ); + let parameters = + turn::sampler_parameters(&sampler_statement(&budgeted(16), Some(closed))).unwrap(); + assert!(parameters[turn::REASONING].is_null(), "{parameters}"); + // the budget the request resolved to is still stated + assert_eq!(parameters["reasoning_budget"], 16); + } + + #[test] + fn a_turn_that_ignores_its_end_is_not_greedy() { + // the runtime takes the end tokens out of its candidates, so the + // best logit may not be the token it took + let cold = SamplingConfig { + enabled: true, + temperature: 0.0, + ignore_eos: true, + ..SamplingConfig::default() + }; + assert!(!greedy_sampling(&cold, None)); + let mut drawn = cold.clone(); + make_draw_replayable(&mut drawn, None, Some(99)); + // a temperature of 0 at the end of the chain takes the best logit + assert!(!drawn.indexed_draw); + let parameters = turn::sampler_parameters(&sampler_statement(&drawn, None)).unwrap(); + assert_eq!(parameters["ignore_eos"], true); + assert!(parameters["draw"].is_null()); + } + + #[test] + fn a_turn_states_the_chain_the_runtime_ran() { + // a request that names an empty chain runs the default one + let empty = SamplingConfig { + samplers: Vec::new(), + top_p: 1.0, + ..warm() + }; + let parameters = turn::sampler_parameters(&sampler_statement(&empty, None)).unwrap(); + assert_eq!( + parameters["samplers"], + serde_json::json!([ + "penalties", + "dry", + "top_n_sigma", + "top_k", + "min_p", + "xtc", + "temperature" + ]) + ); + // a turn with sampling off ran at a temperature of 0 + let off = SamplingConfig { + enabled: false, + temperature: 1.0, + ..budgeted(16) + }; + let parameters = turn::sampler_parameters(&sampler_statement(&off, None)).unwrap(); + assert_eq!(parameters["temperature"], 0.0); + } + + #[test] + fn the_last_sampler_draws_as_the_runtime_decides() { + let with = |samplers: &[&str], temperature: f32, top_k: i32| SamplingConfig { + samplers: samplers.iter().map(|s| (*s).to_owned()).collect(), + temperature, + top_k, + logit_bias: vec![skippy_runtime::LogitBias { + token_id: 3, + bias: 1.0, + }], + ..warm() + }; + assert!(last_sampler_draws(&with( + &["top_k", "temperature"], + 0.7, + 40 + ))); + assert!(!last_sampler_draws(&with( + &["top_k", "temperature"], + 0.0, + 40 + ))); + // a chain that ends in a top-k of 1 takes the best logit + assert!(!last_sampler_draws(&with( + &["temperature", "top_k"], + 0.7, + 1 + ))); + // a chain without a temperature draws at any stated temperature + assert!(last_sampler_draws(&with(&["top_k"], 0.0, 40))); + // a dynamic temperature draws at a base of 0 + let dynamic = SamplingConfig { + dynatemp_range: 0.5, + ..with(&["top_k", "temperature"], 0.0, 40) + }; + assert!(last_sampler_draws(&dynamic)); + } + + #[test] + fn the_receipt_seed_beats_a_default_and_the_body_beats_both() { + let defaulted = SamplingConfig { seed: 5, ..warm() }; + // the operator's default seed 5 filled in a body without one + assert_eq!( + prefer_receipt_seed(defaulted.clone(), None, Some(99)).seed, + 99 + ); + // the body named 5 itself + assert_eq!( + prefer_receipt_seed(defaulted.clone(), Some(5), Some(99)).seed, + 5 + ); + // no receipt seed, or seed 0, leaves the default + assert_eq!(prefer_receipt_seed(defaulted.clone(), None, None).seed, 5); + assert_eq!(prefer_receipt_seed(defaulted, None, Some(0)).seed, 5); + // a turn without any seed takes the receipt's when it draws + let mut unseeded = prefer_receipt_seed(warm(), None, Some(99)); + assert_eq!(unseeded.seed, 0); + make_draw_replayable(&mut unseeded, None, Some(99)); + assert_eq!(unseeded.seed, 99); + } +} diff --git a/crates/skippy-serving/src/receipts/tests.rs b/crates/skippy-serving/src/receipts/tests.rs new file mode 100644 index 00000000..208083c8 --- /dev/null +++ b/crates/skippy-serving/src/receipts/tests.rs @@ -0,0 +1,1142 @@ +//! Fixtures for the receipts tests, and the tests of a stage's turn +//! lifecycle. The routes, the stage connection and the downstream client +//! have their tests beside them. + +use std::collections::BTreeMap; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use skippy_protocol::binary::ReceiptsReply; +use skippy_receipts::binding::{verify_paths, verify_shape}; +use skippy_receipts::layer_tensors::{ + GGML_F32, TensorColumn, TensorKind, UbatchColumns, f32_bytes, +}; +use skippy_receipts::recorder::{ + CHALLENGE_PIN, FIRM_PIN, KvCell, MemoryOp, PrefixCell, Recorder, ReplayScope, ReplaySeed, + ReplayStep, ReplayedLayer, ReplayedPosition, Replayer, StoredRows, TurnId, UbatchRecord, +}; +use skippy_receipts::wire::{CannotOpen, CannotOpenReason, Challenge, Pick, Receipt}; + +use super::downstream::{ChainRequest, CommitRequest, Downstream, HttpDownstream}; +use super::http_api::{ApiState, router, spawn_api}; +use super::kept_turns::KeptTurns; +use super::refusal::NotFound; +use super::reply_limits::ReplyLimits; +use super::{SessionTurn, SessionTurns, StageReceipts, StageReplayer, TurnTokens, lock}; + +pub(super) const SESSION: &str = "session-a"; +pub(super) const SEQ: i32 = 3; +pub(super) const POSITIONS: std::ops::Range = 4..10; +/// A bound on every wait for something another thread does. +pub(super) const GENEROUS: Duration = Duration::from_secs(60); + +pub(super) fn turn() -> TurnTokens { + TurnTokens { + generation_start: 7, + final_token: Some(42), + sampled: 4, + sampler: skippy_receipts::turn::GREEDY.to_owned(), + } +} + +pub(super) struct FixedSessions(BTreeMap); + +impl SessionTurns for FixedSessions { + fn turn(&self, session: &str) -> Option { + self.0.get(session).map(|&seq| SessionTurn { + seq, + turn: TurnId::default(), + }) + } +} + +/// The sessions every fixture stage serves. The routes hold them weakly, as +/// they hold a stage's runtime. +pub(super) fn sessions() -> Arc { + static SESSIONS: LazyLock> = + LazyLock::new(|| Arc::new(FixedSessions(BTreeMap::from([(SESSION.into(), SEQ)])))); + SESSIONS.clone() +} + +/// The turn the fixture's session computes. +pub(super) fn session_turn() -> SessionTurn { + sessions().turn(SESSION).expect("the fixture session") +} + +const KINDS: [TensorKind; 5] = [ + TensorKind::Residual, + TensorKind::MixingInput, + TensorKind::MixingOutput, + TensorKind::MatmulInput, + TensorKind::MatmulOutput, +]; + +/// One tensor of each kind in every layer, derived from the position: what +/// a deterministic model would compute. +struct SyntheticColumns(BTreeMap<(u32, TensorKind, usize), Vec>); + +impl SyntheticColumns { + fn new(record: &UbatchRecord) -> Self { + let mut values = BTreeMap::new(); + for (col, &pos) in record.pos.iter().enumerate() { + for layer in 0..5 { + for kind in KINDS { + let value = pos as f32 + layer as f32 / 100.0 + kind.code() as f32 / 1000.0; + values.insert((layer, kind, col), f32_bytes(&[value, value + 1.0])); + } + } + } + Self(values) + } +} + +impl UbatchColumns for SyntheticColumns { + fn count(&self, _layer: u32, kind: TensorKind) -> u32 { + u32::from(KINDS.contains(&kind)) + } + + fn column( + &self, + layer: u32, + kind: TensorKind, + index: u32, + col: usize, + ) -> Option> { + let bytes = self.0.get(&(layer, kind, col)).filter(|_| index == 0)?; + Some(TensorColumn { + ggml_type: GGML_F32, + flags: 0, + name: "blk.w.weight", + bytes, + digest: None, + }) + } +} + +/// What a fixture stage's replayer was asked to do. +#[derive(Default)] +pub(super) struct Probe { + /// Replays run. + pub replays: AtomicUsize, + /// The number of cells of every pin, in order. + pub pins: Mutex>, + /// The cells pinned when each replay ran. + pub pinned_in_replays: Mutex>, +} + +impl Probe { + pub(super) fn replays(&self) -> usize { + self.replays.load(Ordering::SeqCst) + } + + /// The cells pinned now. + pub(super) fn pinned(&self) -> usize { + lock(&self.pins).last().copied().unwrap_or(0) + } +} + +/// Replays by recomputing the synthetic values. Like the native replayer, +/// it starts a replay only from cells the recorder still knows. +struct SyntheticReplayer { + probe: Arc, + recorder: Arc, +} + +impl Replayer for SyntheticReplayer { + fn replay( + &self, + seq: i32, + layers: &[u32], + _scope: ReplayScope<'_>, + seed: Option<&ReplaySeed>, + steps: &[ReplayStep], + ) -> Result> { + self.probe.replays.fetch_add(1, Ordering::SeqCst); + let pinned = self.probe.pinned(); + lock(&self.probe.pinned_in_replays).push(pinned); + if let Some(seed) = seed { + self.recorder.check_seed(seed)?; + } + let mut out = Vec::new(); + for step in steps { + if let ReplayStep::Decode { + record, capture, .. + } = step + { + for col in 0..record.pos.len() { + let position = u32::try_from(record.pos[col])?; + if record.seq[col] == seq && capture.contains(&position) { + let columns = SyntheticColumns::new(record); + for &layer in layers { + let values = ReplayedLayer::from_columns(layer, &columns, col)?; + out.push((position, layer, values)); + } + } + } + } + } + Ok(out) + } + + /// The synthetic layers store no rows. + fn read_rows(&self, _layer: u32, _cells: &[PrefixCell]) -> Result> { + Ok(Vec::new()) + } + + fn pin_cells(&self, cells: &[KvCell]) -> Result<()> { + lock(&self.probe.pins).push(cells.len()); + Ok(()) + } +} + +impl StageReplayer for SyntheticReplayer {} + +/// Records `positions` of the fixture's sequence on `receipts`. +pub(super) fn record(receipts: &StageReceipts, positions: std::ops::Range) { + let n = positions.len(); + let record = UbatchRecord { + token: positions.clone().map(|p| 100 + p as i32).collect(), + seq: vec![SEQ; n], + pos: positions.clone().map(|p| p as i32).collect(), + output: vec![1; n], + cell: positions.collect(), + n_kv: 256, + input: None, + }; + let columns = SyntheticColumns::new(&record); + receipts.reports.recorder().record_ubatch(record, &columns); +} + +/// A stage that recorded the fixture's turn at [`POSITIONS`], after an +/// earlier turn it attends to, and the probe of its replayer. +pub(super) fn probed_stage( + index: u32, + layers: std::ops::Range, + downstream: Option>, +) -> (StageReceipts, Arc) { + let receipts = StageReceipts::new( + index, + layers, + "test".into(), + downstream, + "model.gguf".into(), + ed25519_dalek::SigningKey::from_bytes(&[index as u8 + 1; 32]), + ReplyLimits::for_width(Some(2)), + ); + let probe = Arc::new(Probe::default()); + receipts.set_replayer(Box::new(SyntheticReplayer { + probe: probe.clone(), + recorder: receipts.reports.shared_recorder(), + })); + record(&receipts, 0..POSITIONS.start); + receipts + .reports + .recorder() + .commit("earlier", SEQ, TurnId::default(), 0..POSITIONS.start) + .expect("earlier turn"); + record(&receipts, POSITIONS); + (receipts, probe) +} + +pub(super) fn stage( + index: u32, + layers: std::ops::Range, + downstream: Option>, +) -> StageReceipts { + probed_stage(index, layers, downstream).0 +} + +pub(super) fn api_state(receipts: &Arc) -> ApiState { + let sessions: Arc = sessions(); + ApiState { + receipts: Arc::downgrade(receipts), + sessions: Arc::downgrade(&sessions), + } +} + +/// Serves `routes` on an ephemeral loopback port for the rest of the test +/// run, and returns its URL. +pub(super) fn serve_routes(routes: axum::Router) -> String { + let listener = + std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).expect("bind"); + let url = format!("http://{}", listener.local_addr().expect("address")); + std::mem::forget(spawn_api(listener, routes).expect("serve")); + url +} + +/// Serves the receipts API of `receipts`, which the test run keeps. +pub(super) fn serve(receipts: StageReceipts) -> String { + let receipts = Arc::new(receipts); + let url = serve_routes(router(api_state(&receipts))); + std::mem::forget(receipts); + url +} + +/// A two-stage chain: stage 0 holds layers 0..2 in process, stage 1 holds +/// layers 2..4 behind its receipts API. +pub(super) struct Chain { + pub stage0: StageReceipts, + pub probe0: Arc, + pub probe1: Arc, + pub downstream: String, +} + +pub(super) fn chain() -> Chain { + let (stage1, probe1) = probed_stage(1, 2..4, None); + let downstream = serve(stage1); + let http = HttpDownstream::new(&downstream, GENEROUS, GENEROUS).expect("client"); + let (stage0, probe0) = probed_stage(0, 0..2, Some(Box::new(http))); + Chain { + stage0, + probe0, + probe1, + downstream, + } +} + +pub(super) fn challenge(receipt_id: &str, layers: &[u32]) -> Challenge { + Challenge { + receipt_id: receipt_id.into(), + picks: layers + .iter() + .map(|&layer| Pick { + layer, + positions: vec![4, 7, 9], + }) + .collect(), + proof: None, + head: Vec::new(), + attention: Vec::new(), + } +} + +pub(super) fn client() -> skippy_receipts::vrf::SecretKey { + skippy_receipts::vrf::SecretKey::from_seed([4; 32]) +} + +pub(super) fn bound_request( + client: &skippy_receipts::vrf::SecretKey, +) -> skippy_inference_api::ReceiptRequest { + skippy_inference_api::ReceiptRequest { + client_key: client.public(), + parent: Some([7; 32]), + seed: None, + id: None, + } +} + +/// Commits the fixture's turn as a receipt bound to [`client`], and +/// returns it with a challenge of `layers` that carries the client's proof. +pub(super) fn bound_turn(stage0: &StageReceipts, id: &str, layers: &[u32]) -> (Receipt, Challenge) { + let client = client(); + let receipt = stage0 + .finish_turn( + id, + SESSION, + session_turn(), + turn(), + Some(bound_request(&client)), + ) + .expect("receipt"); + let root = skippy_receipts::turn::verify(&receipt, None) + .expect("bound") + .turn_root; + let mut challenge = challenge(id, layers); + let proof = client.prove(&skippy_receipts::turn::challenge_input(&root)); + challenge.proof = Some(hex::encode(proof)); + (receipt, challenge) +} + +/// The [`CannotOpen`] a request failed with. +pub(super) fn cannot_open(error: &anyhow::Error) -> &CannotOpen { + error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a cannot-open answer: {error:#}")) +} + +/// Serves the binary stage protocol on an ephemeral loopback port: every +/// connection is told the stage is ready, and each receipts request is +/// answered with what `answer` returns; `None` closes the connection, as a +/// stage that predates receipts does. Returns the endpoint and the count of +/// accepted connections. +pub(super) fn fake_stage( + answer: impl Fn(&ChainRequest) -> Option + Send + Sync + 'static, +) -> (String, Arc) { + let listener = + std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).expect("bind"); + let endpoint = format!("tcp://{}", listener.local_addr().expect("address")); + let accepted = Arc::new(AtomicUsize::new(0)); + let count = accepted.clone(); + let answer = Arc::new(answer); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + count.fetch_add(1, Ordering::SeqCst); + let answer = answer.clone(); + std::thread::spawn(move || { + use skippy_protocol::binary::{ + read_stage_message, send_ready, send_receipts_reply, + }; + if send_ready(&mut stream).is_err() { + return; + } + while let Ok(message) = read_stage_message(&mut stream, 0) { + let request = serde_json::from_slice(&message.raw_bytes).expect("a request"); + let Some(reply) = answer(&request) else { + return; + }; + if send_receipts_reply(&mut stream, &reply).is_err() { + return; + } + } + }); + } + }); + (endpoint, accepted) +} + +pub(super) fn stage_config(downstream: &str) -> skippy_protocol::StageConfig { + skippy_protocol::StageConfig { + bind_addr: "127.0.0.1:0".into(), + downstream: Some(skippy_protocol::PeerConfig { + stage_id: "stage-1".into(), + stage_index: 1, + endpoint: downstream.into(), + persistent_lane_marker: false, + }), + ..Default::default() + } +} + +#[test] +fn finish_turn_commits_every_stage() { + let Chain { stage0, .. } = chain(); + let receipt = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + + assert_eq!(receipt.model, "model.gguf"); + assert_eq!( + receipt.tokens, + POSITIONS.map(|p| 100 + p as i32).collect::>() + ); + assert_eq!(receipt.sampled_tokens(), vec![107, 108, 109, 42]); + assert_eq!( + (receipt.position_start, receipt.position_end), + (POSITIONS.start, POSITIONS.end) + ); + let layers: Vec<_> = receipt + .stages + .iter() + .map(|stage| (stage.stage_index, stage.layer_start, stage.layer_end)) + .collect(); + assert_eq!(layers, [(0, 0, 2), (1, 2, 4)]); + assert_eq!(stage0.receipt("r1"), Some(Ok(Arc::new(receipt)))); +} + +#[test] +fn opens_every_stage_of_the_chain() { + let Chain { stage0, .. } = chain(); + let receipt = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + verify_shape(&receipt, 4).expect("shape"); + + for layers in [&[1, 3][..], &[0], &[2, 3]] { + let challenge = challenge("r1", layers); + let opening = stage0.open(&challenge, None).expect("opening"); + let stages: Vec = opening.stages.iter().map(|s| s.stage_index).collect(); + assert_eq!(stages, [0, 1]); + assert_eq!(opening.stages[0].anchors.len(), 3); + verify_paths(&receipt, &challenge, &opening).expect("paths verify"); + } +} + +#[test] +fn rejects_layers_and_receipts_nobody_holds() { + let Chain { stage0, .. } = chain(); + stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + + assert!(stage0.open(&challenge("r1", &[1, 9]), None).is_err()); + let error = stage0.open(&challenge("missing", &[3]), None).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + assert!(stage0.receipt("missing").is_none()); +} + +#[test] +fn refuses_a_remote_bind_unless_allowed() { + let mut options = super::ReceiptsOptions { + listen: Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 9501))), + allow_remote: false, + downstream: None, + claimed_model: "model.gguf".into(), + signing_key: None, + }; + assert!(super::check_listen(&options).is_err()); + options.allow_remote = true; + assert!(super::check_listen(&options).is_ok()); + options.allow_remote = false; + options.listen = Some(SocketAddr::from((Ipv4Addr::LOCALHOST, 9501))); + assert!(super::check_listen(&options).is_ok()); + options.listen = None; + assert!(super::check_listen(&options).is_ok()); +} + +// The node's key seed is a secret: nothing that logs the options shows it. +#[test] +fn the_signing_key_is_not_written_out() { + let options = super::ReceiptsOptions::embedded("model.gguf".into(), Some([0xAB; 32])); + let debug = format!("{options:?} {options:#?}"); + assert!(debug.contains("") && debug.contains("model.gguf")); + assert!(!debug.contains("171") && !debug.to_lowercase().contains("ab, ab")); + let unset = super::ReceiptsOptions::embedded("model.gguf".into(), None); + assert!(format!("{unset:?}").contains("signing_key: None")); +} + +#[test] +fn a_turn_without_a_receipt_keeps_the_reason() { + let Chain { stage0, .. } = chain(); + let other = SessionTurn { + seq: SEQ + 1, + turn: TurnId::default(), + }; + assert!( + stage0 + .finish_turn("r2", SESSION, other, turn(), None) + .is_err() + ); + let reason = stage0.receipt("r2").expect("kept").expect_err("no receipt"); + assert!(reason.contains("recorded nothing"), "{reason}"); +} + +// A commit names its turn: a session that names a turn the sequence does +// not record gets no receipt, not the leaves of the turn that is there. +#[test] +fn a_commit_of_another_turn_gets_no_receipt() { + let stage0 = stage(0, 0..4, None); + let stale = SessionTurn { + seq: SEQ, + turn: TurnId(99), + }; + let error = stage0 + .finish_turn("r1", SESSION, stale, turn(), None) + .unwrap_err(); + assert!( + format!("{error:#}").contains("recorded nothing"), + "{error:#}" + ); + // the turn that is there still commits + stage0 + .finish_turn("r2", SESSION, session_turn(), turn(), None) + .expect("receipt"); +} + +#[test] +fn a_bound_receipt_is_signed_and_names_the_client() { + let Chain { stage0, .. } = chain(); + let client = client(); + let receipt = stage0 + .finish_turn( + "r1", + SESSION, + session_turn(), + turn(), + Some(bound_request(&client)), + ) + .expect("receipt"); + let verified = + skippy_receipts::turn::verify(&receipt, Some(&client.public())).expect("bound receipt"); + assert_eq!( + verified.node_key, + stage0.signing_key.verifying_key().to_bytes() + ); + let binding = receipt.binding.expect("binding"); + assert_eq!(binding.parent, Some(hex::encode([7; 32]))); + assert!(binding.runtime.starts_with("skippy-abi ")); +} + +#[test] +fn a_bound_receipt_opens_one_challenge_with_its_proof() { + let Chain { stage0, .. } = chain(); + let client = client(); + let (receipt, challenge) = bound_turn(&stage0, "r1", &[1, 3]); + let mut unproven = challenge.clone(); + unproven.proof = None; + let err = stage0.open(&unproven, None).expect_err("no proof"); + assert!(format!("{err:#}").contains("VRF proof"), "{err:#}"); + + // a proof of another input does not open it + let mut wrong = challenge.clone(); + wrong.proof = Some(hex::encode(client.prove(b"another root"))); + assert!(stage0.open(&wrong, None).is_err()); + + let opening = stage0.open(&challenge, None).expect("opening"); + verify_paths(&receipt, &challenge, &opening).expect("paths verify"); + // stage 0 signs the opening it sends, for a bound receipt only + let bytes = serde_json::to_vec(&opening).unwrap(); + let signature = stage0 + .sign_opening(&challenge, &bytes) + .unwrap() + .expect("signed"); + let bound = skippy_receipts::turn::verify(&receipt, None).unwrap(); + skippy_receipts::turn::verify_opening(&bound, &challenge, &bytes, &signature) + .expect("signature"); + // the same challenge again is fine; another one is not + stage0.open(&challenge, None).expect("repeat"); + let mut other = self::challenge("r1", &[0]); + other.proof = challenge.proof.clone(); + let err = stage0.open(&other, None).expect_err("second challenge"); + assert!(format!("{err:#}").contains("already challenged"), "{err:#}"); +} + +// The attention rows of a bound receipt follow its signed opening, and only +// the client's VRF of that opening reads them. +#[test] +fn a_bound_receipt_opens_rows_only_for_the_clients_draw() { + use skippy_receipts::attention::opening::BlockChallenge; + use skippy_receipts::turn; + let Chain { stage0, .. } = chain(); + let client = client(); + let (receipt, challenge) = bound_turn(&stage0, "r1", &[1, 3]); + let bound = turn::verify(&receipt, None).expect("bound"); + let mut rows = BlockChallenge { + receipt_id: "r1".into(), + picks: Vec::new(), + proof: Some(hex::encode(client.prove(b"anything"))), + }; + let err = stage0.rows(&rows, None).expect_err("not opened"); + assert!(format!("{err:#}").contains("was not opened"), "{err:#}"); + + let opening = stage0.open(&challenge, None).expect("opening"); + // opened, but stage 0 has not signed an opening yet + assert!(stage0.rows(&rows, None).is_err()); + let bytes = serde_json::to_vec(&opening).unwrap(); + stage0 + .sign_opening(&challenge, &bytes) + .unwrap() + .expect("signed"); + + // a proof of another input does not read them, nor does none + assert!(stage0.rows(&rows, None).is_err()); + rows.proof = None; + assert!(stage0.rows(&rows, None).is_err()); + rows.proof = Some(hex::encode(client.prove(&turn::rows_input(&bytes)))); + let opened = stage0.rows(&rows, None).expect("rows"); + assert_eq!(opened.receipt_id, "r1"); + let rows_bytes = serde_json::to_vec(&opened).unwrap(); + let signature = stage0 + .sign_rows(&rows, &rows_bytes) + .unwrap() + .expect("signed"); + turn::verify_rows(&bound, &rows, &rows_bytes, &signature).expect("signature"); + // the rows' signature is not an opening's + assert!(turn::verify_opening(&bound, &challenge, &rows_bytes, &signature).is_err()); + + // rows of a position the challenge did not pick for attention are refused + let mut unasked = rows.clone(); + unasked.picks = vec![skippy_receipts::attention::opening::BlockPick { + position: 4, + layer: 1, + blocks: vec![0], + }]; + let err = stage0.rows(&unasked, None).expect_err("blocks nobody drew"); + assert!(format!("{err:#}").contains("attention pick"), "{err:#}"); +} + +#[test] +fn a_turn_ends_at_the_last_token_it_fed() { + // the last verify window computed drafts at 10 and 11, rejected when + // the turn stopped + assert_eq!(super::turn_positions(4..12, &turn()).unwrap(), 4..10); + assert_eq!( + super::turn_positions(POSITIONS, &turn()).unwrap(), + POSITIONS + ); + let unsampled = TurnTokens { + sampled: 0, + ..turn() + }; + assert_eq!(super::turn_positions(4..12, &unsampled).unwrap(), 4..12); +} + +// A ubatch the recorder could not receipt, such as one of image embeddings, +// computed the turn's last positions: the receipt would stop short of the +// position its last token was sampled from, so there is none. +#[test] +fn a_turn_that_did_not_record_its_last_fed_position_gets_no_receipt() { + let error = super::turn_positions(4..8, &turn()).unwrap_err(); + assert!(format!("{error:#}").contains("up to 10"), "{error:#}"); +} + +// Only a receipt a client can challenge keeps its cells out of later +// requests' way. +#[test] +fn only_a_bound_turn_pins_its_cells() { + let pinned = |stage: &StageReceipts| { + let recorder = stage.reports.recorder(); + // the fixture's earlier turn + recorder.release_pin("earlier"); + recorder.pinned_cells(Instant::now()) + }; + let unbound = chain().stage0; + unbound + .finish_turn("unbound", SESSION, session_turn(), turn(), None) + .expect("receipt"); + assert!(pinned(&unbound).is_empty()); + let bound = chain().stage0; + bound_turn(&bound, "bound", &[1]); + assert!(!pinned(&bound).is_empty()); +} + +// A turn's cells are pinned natively no longer than its pin holds: the +// stage pins anew when the pin runs out, not only at its next commit. +#[test] +fn pins_are_given_up_when_they_run_out() { + let (stage0, probe) = probed_stage(0, 0..4, None); + stage0.reports.recorder().release_pin("earlier"); + bound_turn(&stage0, "bound", &[1]); + assert!(probe.pinned() > 0); + let now = Instant::now(); + // the stage looks again when the pin starts to linger, and when it ends + let lingers = stage0.run_upkeep(now).expect("a pin that will linger"); + assert!(probe.pinned() > 0 && lingers > now && lingers <= now + FIRM_PIN); + let due = stage0.run_upkeep(lingers).expect("a pin to give up"); + assert!(probe.pinned() > 0 && due > lingers && due <= now + CHALLENGE_PIN); + assert_eq!(stage0.run_upkeep(due), None, "nothing is pinned any more"); + assert_eq!(probe.pinned(), 0); +} + +// A challenge pins its turn's cells while it waits and is opened, also +// when the turn has no pin of its own: the opening reads the cells after +// the replay, and a later request must not write them meanwhile. +#[test] +fn an_opening_pins_its_turn_while_it_replays() { + let (stage0, probe) = probed_stage(0, 0..4, None); + stage0.reports.recorder().release_pin("earlier"); + stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), None) + .expect("receipt"); + // a turn bound to no key has no pin of its own + assert_eq!(probe.pinned(), 0); + stage0.open(&challenge("r1", &[1]), None).expect("opening"); + let in_replays = lock(&probe.pinned_in_replays).clone(); + assert!( + !in_replays.is_empty() && in_replays.iter().all(|&cells| cells > 0), + "{in_replays:?}" + ); + // an opening without attention picks leaves no rows to read + assert_eq!(probe.pinned(), 0); + + // a challenge the stage refuses pins nothing past its refusal + assert!(stage0.open(&challenge("r1", &[9]), None).is_err()); + assert_eq!(probe.pinned(), 0); +} + +// A turn whose next stage did not commit has no receipt, so stage 0 keeps +// neither the turn nor a pin on its cells. +#[test] +fn a_failed_downstream_commit_leaves_nothing_pinned() { + let (endpoint, _) = fake_stage(|_| Some(ReceiptsReply::Refused("no turn".into()))); + let next = + super::downstream::StageConnection::new(&stage_config(&endpoint), GENEROUS, GENEROUS); + let (stage0, probe) = probed_stage(0, 0..2, Some(Box::new(next))); + stage0.reports.recorder().release_pin("earlier"); + let request = Some(bound_request(&client())); + let error = stage0 + .finish_turn("r1", SESSION, session_turn(), turn(), request) + .unwrap_err(); + assert!(format!("{error:#}").contains("no turn"), "{error:#}"); + assert!(!stage0.reports.recorder().holds_turn("r1")); + assert_eq!(probe.pinned(), 0); + assert!(stage0.receipt("r1").expect("kept").is_err()); +} + +// A challenge no draw makes is refused before the stage replays anything, +// for a bound receipt and for one bound to no key. +#[test] +fn an_oversized_challenge_is_refused_before_any_replay() { + let Chain { + stage0, + probe0, + probe1, + .. + } = chain(); + stage0 + .finish_turn("unbound", SESSION, session_turn(), turn(), None) + .expect("receipt"); + let every_position = |id: &str, proof: Option| Challenge { + receipt_id: id.into(), + picks: (0..4) + .map(|layer| Pick { + layer, + positions: POSITIONS.collect(), + }) + .collect(), + proof, + head: Vec::new(), + attention: Vec::new(), + }; + let error = stage0 + .open(&every_position("unbound", None), None) + .unwrap_err(); + assert!(format!("{error:#}").contains("a draw picks"), "{error:#}"); + + let bound = chain(); + let (_, drawn) = bound_turn(&bound.stage0, "bound", &[1, 3]); + let oversized = every_position("bound", drawn.proof.clone()); + let error = bound.stage0.open(&oversized, None).unwrap_err(); + assert!(format!("{error:#}").contains("a draw picks"), "{error:#}"); + // the refused challenge was not the one challenge the receipt gets + bound + .stage0 + .open(&drawn, None) + .expect("the drawn challenge"); + + assert_eq!(probe0.replays() + probe1.replays(), 0); + assert!( + bound.probe0.replays() > 0, + "only the drawn one was replayed" + ); +} + +// A receipt id the stage keeps no record of is refused as not found, also +// when the recorder still holds the turn: it is never opened without the +// proof its record would have asked for. +#[test] +fn an_evicted_receipt_is_not_opened() { + let (stage0, probe) = probed_stage(0, 0..4, None); + let (_, challenge) = bound_turn(&stage0, "r1", &[1]); + // the record is dropped, as when its window has passed + *lock(&stage0.kept) = KeptTurns::default(); + assert!(stage0.reports.recorder().holds_turn("r1")); + let mut unproven = challenge.clone(); + unproven.proof = None; + for challenge in [&challenge, &unproven] { + let error = stage0.open(challenge, None).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + } + let rows = skippy_receipts::attention::opening::BlockChallenge { + receipt_id: "r1".into(), + picks: Vec::new(), + proof: None, + }; + let error = stage0.rows(&rows, None).unwrap_err(); + assert!(error.downcast_ref::().is_some(), "{error:#}"); + assert_eq!(probe.replays(), 0); + assert_eq!(stage0.sign_opening(&challenge, b"{}").unwrap(), None); +} + +// A request id that comes back while its receipt can still be challenged +// gets no receipt, whoever asks: another client cannot shadow the receipt, +// and the client it was signed for can still open it. +#[test] +fn a_reused_request_id_keeps_the_receipt_that_can_still_be_challenged() { + let stage0 = stage(0, 0..4, None); + let (first, challenge) = bound_turn(&stage0, "r1", &[1]); + stage0 + .open(&challenge, None) + .expect("the first turn's challenge"); + + // another client asks for a turn under the same id + record(&stage0, POSITIONS.end..POSITIONS.end + 2); + let intruder = skippy_receipts::vrf::SecretKey::from_seed([9; 32]); + let error = stage0 + .finish_turn( + "r1", + SESSION, + session_turn(), + turn(), + Some(bound_request(&intruder)), + ) + .unwrap_err(); + assert!(format!("{error:#}").contains("another client"), "{error:#}"); + let kept = stage0.receipt("r1").expect("a record").expect("a receipt"); + assert_eq!(kept.stages, first.stages); + stage0 + .open(&challenge, None) + .expect("still the first turn's"); + + // the first client's next turn under the id, inside the window: the + // receipt it was signed stays the one the id opens + let tokens = TurnTokens { + generation_start: POSITIONS.end + 1, + sampled: 2, + ..turn() + }; + let error = stage0 + .finish_turn( + "r1", + SESSION, + session_turn(), + tokens, + Some(bound_request(&client())), + ) + .unwrap_err(); + assert!( + format!("{error:#}").contains("signed a receipt"), + "{error:#}" + ); + // a lookup by id returns a bound receipt without the turn's tokens + let kept = Receipt { + tokens: Vec::new(), + final_token: None, + ..first + }; + assert_eq!(stage0.receipt("r1"), Some(Ok(Arc::new(kept)))); + stage0 + .open(&challenge, None) + .expect("still the first turn's"); +} + +// A stage after the first opens a bound turn only with the client's proof, +// and what it refuses costs the turn none of its replays. +#[test] +fn a_later_stage_asks_for_the_clients_proof() { + let (stage1, probe) = probed_stage(1, 2..4, None); + let client = client(); + let commit = CommitRequest { + receipt_id: "r1".into(), + session: SESSION.into(), + position_start: POSITIONS.start, + position_end: POSITIONS.end, + client_key: Some(hex::encode(client.public())), + }; + stage1 + .commit_session(sessions().as_ref(), &commit) + .expect("commit"); + let root = [5; 32]; + let proof = hex::encode(client.prove(&skippy_receipts::turn::challenge_input(&root))); + let forwarded = |challenge: &Challenge, root: Option<[u8; 32]>| super::ForwardedOpen { + challenge: challenge.clone(), + turn_root: root.map(hex::encode), + }; + let unproven = challenge("r1", &[3]); + let mut proven = unproven.clone(); + proven.proof = Some(proof); + let mut forged = unproven.clone(); + let stranger = skippy_receipts::vrf::SecretKey::from_seed([9; 32]); + let stolen = stranger.prove(&skippy_receipts::turn::challenge_input(&root)); + forged.proof = Some(hex::encode(stolen)); + // more refused opens than a receipt gets replays + for _ in 0..2 * skippy_receipts::recorder::MAX_REPLAYS_PER_RECEIPT { + for refused in [ + forwarded(&unproven, Some(root)), + forwarded(&forged, Some(root)), + forwarded(&proven, None), + forwarded(&proven, Some([6; 32])), + ] { + assert!(stage1.open_forwarded(&refused).is_err()); + } + } + assert_eq!(probe.replays(), 0); + + let opening = stage1 + .open_forwarded(&forwarded(&proven, Some(root))) + .expect("the client's challenge"); + assert_eq!(opening.stages[0].layers[0].layer, 3); + assert_eq!(probe.replays(), 1); + // the same challenge again is answered from the opening kept + stage1 + .open_forwarded(&forwarded(&proven, Some(root))) + .expect("repeat"); + assert_eq!(probe.replays(), 1); + // one challenge per bound turn, on every stage + let mut other = challenge("r1", &[2]); + other.proof = proven.proof.clone(); + let error = stage1 + .open_forwarded(&forwarded(&other, Some(root))) + .unwrap_err(); + assert!( + format!("{error:#}").contains("already challenged"), + "{error:#}" + ); +} + +// When the stage's own cache no longer holds a turn, it says that it cannot +// open it and why, which is not how it refuses a request. +#[test] +fn a_stage_that_lost_a_turns_cells_says_it_cannot_open() { + let stage0 = stage(0, 0..4, None); + let (_, challenge) = bound_turn(&stage0, "r1", &[1]); + let recorder = stage0.reports.recorder(); + // the session ended and the stage could not pin its cells, then a + // ubatch the recorder could not follow + recorder.memory_op(MemoryOp::SeqRm, SEQ, -1, -1, -1); + recorder.pins_not_applied(); + recorder.unreceiptable("two lanes in one recurrent ubatch"); + let error = stage0.open(&challenge, None).unwrap_err(); + let cannot = cannot_open(&error); + assert_eq!(cannot.reason, CannotOpenReason::CellsUnknown); + assert_eq!((cannot.receipt_id.as_str(), cannot.stage_index), ("r1", 0)); + + // a turn that left the recorder's window + let stage0 = stage(0, 0..4, None); + let (_, challenge) = bound_turn(&stage0, "r1", &[1]); + stage0.reports.recorder().discard("r1"); + let error = stage0.open(&challenge, None).unwrap_err(); + assert_eq!(cannot_open(&error).reason, CannotOpenReason::Expired); +} + +// The stage owns its receipts: when it goes, the recorder state and the +// receipts threads go with it, whatever the model's recorder sink, a kept +// router or the API thread still point at. +#[test] +fn dropping_the_stage_drops_its_receipts() { + use skippy_runtime::{ReceiptMemoryEvent, ReceiptRecorderSink}; + let receipts = Arc::new(stage(0, 0..4, None)); + let recorder = Arc::downgrade(&receipts.reports.shared_recorder()); + // what the native recorder holds for as long as the model lives + let sink: Arc = Arc::new(super::native::RecorderSink::new(&receipts)); + receipts.start_upkeep().expect("upkeep"); + let listener = + std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).expect("bind"); + let address = listener.local_addr().expect("address"); + let mut api = spawn_api(listener, router(api_state(&receipts))).expect("serve"); + let api_thread = api.take_thread(); + assert!(receipts.api.set(api).is_ok()); + let client_routes = super::http_api::client_routes(api_state(&receipts)); + let url = format!("http://{address}/receipts/r1"); + let reply = reqwest::blocking::get(&url).expect("reply"); + assert_eq!(reply.status(), reqwest::StatusCode::NOT_FOUND); + + drop(receipts); + assert!(recorder.upgrade().is_none(), "the recorder state is gone"); + // the model may still report, into nothing + sink.memory(&ReceiptMemoryEvent { + op: 0, + seq: -1, + seq_dst: -1, + p0: -1, + p1: -1, + }); + sink.unreceiptable("the stage is gone"); + drop(client_routes); + // the API thread was told to stop when the receipts dropped + api_thread.join().expect("the receipts API thread"); + assert!(std::net::TcpStream::connect(address).is_err()); +} + +#[path = "prefix_tests.rs"] +mod prefix_tests; + +#[test] +fn a_turn_must_compute_the_end_of_its_prompt() { + // a prompt of 10 tokens whose first 9 were cached: the turn computed + // the last one and sampled its first token from it + assert!(super::check_turn_start(10, &(9..14)).is_ok()); + // the whole prompt cached: no receipt covers where the first token + // came from + let error = super::check_turn_start(10, &(10..14)).unwrap_err(); + assert!( + format!("{error:#}").contains("no receipt covers"), + "{error:#}" + ); + // a cached prefix longer than the prompt + assert!(super::check_turn_start(8, &(10..14)).is_err()); + // a turn that fed nothing past its prompt and sampled only its last + // token is a turn of no positions, which no stage commits + assert!(super::check_turn_start(10, &(10..10)).is_ok()); +} + +/// A client that names its receipt id (`x-receipt-id`) gets its receipt +/// under it; else under the request's id, as before. +#[test] +fn a_receipt_is_issued_under_the_id_the_client_asked_for() { + let asked = uuid::Uuid::parse_str("0b0e7c1e-58a5-4b3f-9c36-0d2f6f1f8a10").unwrap(); + let request = [9; 16]; + assert_eq!( + super::issued_id(Some(asked), Some(request), 5), + "0b0e7c1e-58a5-4b3f-9c36-0d2f6f1f8a10" + ); + assert_eq!( + super::issued_id(None, Some(request), 5), + uuid::Uuid::from_bytes(request).hyphenated().to_string() + ); + assert_eq!(super::issued_id(None, None, 5), "0000000000000005"); +} + +/// A hybrid stage gives a turn that continues a cached prefix no receipt, +/// so an embedder that owes one for every turn reads that it keeps +/// recurrent state. A runtime without receipts keeps none for them. +#[test] +fn a_runtime_says_whether_its_receipts_keep_recurrent_state() { + let runtime = Arc::new(Mutex::new( + crate::runtime_state::RuntimeState::new_modelless_for_test(1), + )); + assert!(!super::keeps_recurrent_state(&runtime)); + let receipts = Arc::new(StageReceipts::for_test(0)); + lock(&runtime).set_receipts(receipts.clone()); + assert!(!super::keeps_recurrent_state(&runtime)); + receipts.reports.recorder().set_recurrent(true); + assert!(super::keeps_recurrent_state(&runtime)); +} + +/// A replayer whose first pin waits, once it has begun, until it is let go. +struct GatedPins { + entered: Mutex>, + go: Mutex>, +} + +impl Replayer for GatedPins { + fn replay( + &self, + _seq: i32, + _layers: &[u32], + _scope: ReplayScope<'_>, + _seed: Option<&ReplaySeed>, + _steps: &[ReplayStep], + ) -> Result> { + Ok(Vec::new()) + } + + fn read_rows(&self, _layer: u32, _cells: &[PrefixCell]) -> Result> { + Ok(Vec::new()) + } + + fn pin_cells(&self, _cells: &[KvCell]) -> Result<()> { + let _ = lock(&self.entered).send(()); + let _ = lock(&self.go).recv_timeout(GENEROUS); + Ok(()) + } +} + +impl StageReplayer for GatedPins {} + +// Each pin replaces the whole native pin set, so a snapshot of the pins is +// not taken while an older one is still being published: the older one +// would land last and unpin the turn the newer one covers. +#[test] +fn a_pin_is_published_before_the_next_is_taken() { + let receipts = Arc::new(StageReceipts::new( + 0, + 0..2, + "test".into(), + None, + "model.gguf".into(), + ed25519_dalek::SigningKey::from_bytes(&[1; 32]), + ReplyLimits::for_width(Some(2)), + )); + let (entered, entered_rx) = std::sync::mpsc::channel(); + let (go, go_rx) = std::sync::mpsc::channel(); + receipts.set_replayer(Box::new(GatedPins { + entered: Mutex::new(entered), + go: Mutex::new(go_rx), + })); + let first = { + let receipts = receipts.clone(); + std::thread::spawn(move || receipts.pin_turns(Instant::now())) + }; + entered_rx + .recv_timeout(GENEROUS) + .expect("the first pin began"); + // the lock every pin takes for its snapshot is held until it is published + assert!(receipts.pins_due.try_lock().is_err()); + go.send(()).unwrap(); + first.join().unwrap(); + assert!(receipts.pins_due.try_lock().is_ok()); +} diff --git a/crates/skippy-serving/src/receipts/upkeep.rs b/crates/skippy-serving/src/receipts/upkeep.rs new file mode 100644 index 00000000..41f4c426 --- /dev/null +++ b/crates/skippy-serving/src/receipts/upkeep.rs @@ -0,0 +1,133 @@ +//! One thread per stage for its timed receipt chores: pinning cells anew +//! when a turn's pin runs out, and freeing the replay context once replays +//! stop. It ends when the stage's receipts are dropped, which happens when +//! the model is unloaded. + +use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::Instant; + +#[derive(Default)] +struct Signal { + /// Whether to stop, and whether a chore was asked for since the last run. + state: Mutex<(bool, bool)>, + wake: Condvar, +} + +impl Signal { + fn lock(&self) -> std::sync::MutexGuard<'_, (bool, bool)> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits until `deadline`, a poke or a stop; `false` on a stop. + fn wait(&self, deadline: Option) -> bool { + let mut state = self.lock(); + loop { + if state.0 { + return false; + } + if std::mem::take(&mut state.1) { + return true; + } + state = match deadline { + None => self + .wake + .wait(state) + .unwrap_or_else(PoisonError::into_inner), + Some(deadline) => { + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return true; + }; + self.wake + .wait_timeout(state, left) + .unwrap_or_else(PoisonError::into_inner) + .0 + } + }; + } + } +} + +/// Runs chores on a thread until dropped. +pub(super) struct Upkeep { + signal: Arc, + thread: Option>, +} + +impl Upkeep { + /// Starts a thread that runs `chores` when poked and at the time the + /// last run asked for. `chores` gets the current time and returns when + /// to run next without a poke, or `None` to end the thread: the stage + /// it works for is gone. + pub(super) fn start( + mut chores: impl FnMut(Instant) -> Option> + Send + 'static, + ) -> std::io::Result { + let signal = Arc::new(Signal::default()); + let shared = signal.clone(); + let thread = std::thread::Builder::new() + .name("skippy-receipts-upkeep".into()) + .spawn(move || { + let mut next = None; + while shared.wait(next) { + match chores(Instant::now()) { + Some(deadline) => next = deadline, + None => return, + } + } + })?; + Ok(Self { + signal, + thread: Some(thread), + }) + } + + /// Runs the chores soon: what they time has changed. + pub(super) fn poke(&self) { + self.signal.lock().1 = true; + self.signal.wake.notify_all(); + } +} + +impl Drop for Upkeep { + fn drop(&mut self) { + self.signal.lock().0 = true; + self.signal.wake.notify_all(); + let Some(thread) = self.thread.take() else { + return; + }; + // the chores may hold the last reference to what owns this + if thread.thread().id() != std::thread::current().id() { + let _ = thread.join(); + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + use std::time::Duration; + + use super::*; + + const GENEROUS: Duration = Duration::from_secs(30); + + #[test] + fn chores_run_when_poked_and_when_due_and_end_with_their_owner() { + let (ran, runs) = mpsc::channel(); + let mut due_once = true; + let upkeep = Upkeep::start(move |now| { + ran.send(()).ok()?; + // the first run asks for one more, at once; later ones wait + Some(std::mem::take(&mut due_once).then_some(now)) + }) + .expect("thread"); + upkeep.poke(); + runs.recv_timeout(GENEROUS).expect("the poked run"); + runs.recv_timeout(GENEROUS).expect("the run that was due"); + upkeep.poke(); + runs.recv_timeout(GENEROUS).expect("another poked run"); + drop(upkeep); + // the thread ended and dropped its sender + assert!(runs.recv_timeout(GENEROUS).is_err()); + } +} diff --git a/crates/skippy-serving/src/runtime_state.rs b/crates/skippy-serving/src/runtime_state.rs index b2474931..9a09eacf 100644 --- a/crates/skippy-serving/src/runtime_state.rs +++ b/crates/skippy-serving/src/runtime_state.rs @@ -26,7 +26,9 @@ mod lane_lifecycle; pub mod lifecycle; pub(crate) mod model_content; pub mod panic_recovery; +mod receipt_turns; mod resident_prefix; +pub use receipt_turns::SessionTurn; mod restore_transaction; mod session_end_exports; mod state_transfer; @@ -97,6 +99,10 @@ 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, + /// The turn each session computes, for receipts; see `receipt_turns`. + receipt_turns: receipt_turns::ReceiptTurns, + /// Verifiable inference receipts, when the operator turned them on. + receipts: Option>, #[cfg(test)] modelless_for_test: bool, /// Lets modelless tests exercise a split DFlash final stage. @@ -298,6 +304,8 @@ impl RuntimeState { session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + receipt_turns: receipt_turns::ReceiptTurns::default(), + receipts: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer: None, compute_meter: Arc::default(), @@ -476,6 +484,8 @@ fn runtime_from_loaded_model( session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + receipt_turns: receipt_turns::ReceiptTurns::default(), + receipts: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer, compute_meter: Arc::default(), diff --git a/crates/skippy-serving/src/runtime_state/frame_operations.rs b/crates/skippy-serving/src/runtime_state/frame_operations.rs index 87be2acc..77435b2e 100644 --- a/crates/skippy-serving/src/runtime_state/frame_operations.rs +++ b/crates/skippy-serving/src/runtime_state/frame_operations.rs @@ -851,6 +851,7 @@ impl RuntimeState { lane_session.session.dflash_reset_health(); self.abandon_session_end_kv_exports(session_id); self.sessions.insert(session_id.to_string(), lane_session); + self.note_receipt_sequence(session_id); // Every active session must have a tracked position from the // moment it activates (both a fresh and a reused idle lane start // at native position 0), so `canonical_session_position` is diff --git a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 02a92a20..dd1f6f9f 100644 --- a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -230,6 +230,7 @@ impl RuntimeState { // clear any stray resident-prefix entry under that id. self.session_token_counts.remove(session_id); self.session_resident_prefixes.remove(session_id); + self.release_receipt_turn(session_id); let reset_ms = reset_started.elapsed().as_secs_f64() * 1000.0; // The real decision this function already made: a reset() failure @@ -370,6 +371,7 @@ impl RuntimeState { idle.resident_prefix = None; self.abandon_session_end_kv_exports(session_id); self.sessions.insert(session_id.to_string(), idle); + self.note_receipt_sequence(session_id); self.session_token_counts .insert(session_id.to_string(), token_count); self.session_resident_prefixes.insert( @@ -544,6 +546,7 @@ impl RuntimeState { self.sessions.insert(session_id.to_string(), lane_session); self.session_token_counts .insert(session_id.to_string(), token_ids.len() as u64); + self.note_receipt_sequence(session_id); Ok(()) } diff --git a/crates/skippy-serving/src/runtime_state/receipt_turns.rs b/crates/skippy-serving/src/runtime_state/receipt_turns.rs new file mode 100644 index 00000000..4bc8b9b7 --- /dev/null +++ b/crates/skippy-serving/src/runtime_state/receipt_turns.rs @@ -0,0 +1,184 @@ +//! Which turn of which native sequence each session computes, while the +//! stage issues inference receipts ([`crate::receipts`]). +//! +//! A native sequence serves one session after another, and a session id can +//! come back for a later request. So a session that takes a sequence starts +//! a new turn there, with an identity of its own, which the receipt +//! recorder is told before the session's first ubatch. A commit names the +//! session; the stage resolves it to that turn, and the recorder then takes +//! that turn's log and no other's, also when the sequence has moved on. +//! +//! A session's turn stays resolvable for a few sessions after it ends, for +//! a commit that arrives late; the recorder keeps such a turn's log about +//! as long. + +use std::collections::{BTreeMap, VecDeque}; + +use skippy_receipts::recorder::TurnId; + +use super::*; + +/// Turns of ended sessions that a late commit can still name. +const RELEASED_TURNS: usize = 64; + +/// The turn a session computes: its native sequence, and the identity the +/// receipt recorder knows the turn by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SessionTurn { + pub seq: i32, + pub turn: TurnId, +} + +#[derive(Default)] +pub(super) struct ReceiptTurns { + /// The last identity given out; identities start at 1, and the + /// recorder's default names what no session armed. + last: u64, + /// By session that holds a sequence: its turn. + bound: BTreeMap, + /// Turns of sessions that ended, oldest first. + released: VecDeque<(String, SessionTurn)>, +} + +impl ReceiptTurns { + /// `session` took `seq`: it starts a new turn there. + fn bind(&mut self, session: &str, seq: i32) -> SessionTurn { + self.release(session); + self.last += 1; + let turn = SessionTurn { + seq, + turn: TurnId(self.last), + }; + self.bound.insert(session.to_owned(), turn); + turn + } + + /// `session` ended: its turn stays resolvable for a late commit, until + /// enough sessions have ended after it. + fn release(&mut self, session: &str) { + let Some((session, turn)) = self.bound.remove_entry(session) else { + return; + }; + self.released.push_back((session, turn)); + while self.released.len() > RELEASED_TURNS { + self.released.pop_front(); + } + } + + /// The turn `session` computes, or computed last. + fn turn(&self, session: &str) -> Option { + self.bound.get(session).copied().or_else(|| { + self.released + .iter() + .rev() + .find(|(released, _)| released == session) + .map(|(_, turn)| *turn) + }) + } +} + +impl RuntimeState { + /// A session took a native sequence: while receipts are on, it starts + /// a turn there, which the recorder learns before the session's first + /// ubatch. + pub(super) fn note_receipt_sequence(&mut self, session_id: &str) { + let Some(receipts) = self.receipts.clone() else { + return; + }; + let Some(seq) = self + .sessions + .get(session_id) + .and_then(|lane| lane.session.native_sequence_id().ok()) + else { + return; + }; + self.release_ended_receipt_turns(); + let turn = self.receipt_turns.bind(session_id, seq); + receipts.begin_turn(turn); + } + + /// Releases the turns of sessions that hold no sequence any more, on + /// whatever path they lost it. A session parked for its exports is one + /// of them; its turn stays resolvable like any released one. + fn release_ended_receipt_turns(&mut self) { + let ended: Vec = self + .receipt_turns + .bound + .keys() + .filter(|session| !self.sessions.contains_key(*session)) + .cloned() + .collect(); + for session in ended { + self.receipt_turns.release(&session); + } + } + + /// A session gave up its sequence. + pub(super) fn release_receipt_turn(&mut self, session_id: &str) { + self.receipt_turns.release(session_id); + } + + /// Turns receipts on: later session bindings start turns the recorder + /// knows. + pub fn set_receipts(&mut self, receipts: Arc) { + self.receipts = Some(receipts); + } + + pub fn receipts(&self) -> Option<&Arc> { + self.receipts.as_ref() + } + + /// Whether a stage of a split may take a cached prefix of a prompt on + /// its own, outside a restore that stage 0 runs on every stage. Not + /// while it issues receipts: a receipt names the positions stage 0 + /// computed, so every stage must start the turn where stage 0 does. + pub fn restores_prefixes_alone(&self) -> bool { + self.receipts.is_none() + } + + /// The turn a session computes, or computed last. + pub fn receipt_turn(&self, session_id: &str) -> Option { + self.receipt_turns.turn(session_id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_session_that_takes_a_sequence_starts_a_new_turn() { + let mut turns = ReceiptTurns::default(); + let first = turns.bind("a", 3); + assert_eq!(turns.turn("a"), Some(first)); + // another request's session takes the same sequence + turns.release("a"); + let second = turns.bind("b", 3); + assert_eq!((first.seq, second.seq), (3, 3)); + assert_ne!(first.turn, second.turn); + // a late commit of the first session still names its own turn + assert_eq!(turns.turn("a"), Some(first)); + // a session id that comes back names its new turn + turns.release("b"); + let again = turns.bind("a", 5); + assert_eq!(turns.turn("a"), Some(again)); + assert_ne!(again.turn, first.turn); + assert_eq!(turns.turn("never"), None); + } + + // One session per request must not leave one entry per request. + #[test] + fn ended_sessions_are_forgotten() { + let mut turns = ReceiptTurns::default(); + for request in 0..10 * RELEASED_TURNS { + let session = format!("session-{request}"); + turns.bind(&session, 0); + turns.release(&session); + } + assert!(turns.bound.is_empty()); + assert_eq!(turns.released.len(), RELEASED_TURNS); + assert_eq!(turns.turn("session-0"), None); + let last = format!("session-{}", 10 * RELEASED_TURNS - 1); + assert!(turns.turn(&last).is_some()); + } +} diff --git a/docs/CAUSAL_DECISIONS.md b/docs/CAUSAL_DECISIONS.md index 76baefde..2da05c99 100644 --- a/docs/CAUSAL_DECISIONS.md +++ b/docs/CAUSAL_DECISIONS.md @@ -111,8 +111,8 @@ 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 17, wire header -version 17 and Skippy ABI 0.1.87. Upgrade the whole chain together; older stage +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 ability to an older runtime. No persisted-data migration is required. diff --git a/docs/DATA_FLOW.md b/docs/DATA_FLOW.md index 3bde924a..10293d3d 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 16 is the current compatibility-breaking cutover: a peer is stage compatible only when it -advertises both `skippy-stage/2` and the complete `stage-generation-17` bundle. +advertises both `skippy-stage/2` and the complete `stage-generation-18` 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/RECEIPTS.md b/docs/RECEIPTS.md new file mode 100644 index 00000000..01594dca --- /dev/null +++ b/docs/RECEIPTS.md @@ -0,0 +1,1403 @@ +# Inference receipts + +An inference receipt lets a client check that a serving node ran the model +that it claims to run. This feature is experimental and off by default. + +This guide is for operators who serve with receipts and for users who audit +a node. The design is in +[RECEIPTS.md](design/RECEIPTS.md) and +[RECEIPTS_GLUE.md](design/RECEIPTS_GLUE.md). The limits +that are still open are in +[Open limitations](design/RECEIPTS.md#open-limitations). + +Do not confuse an inference receipt with the generation receipt in +`skippy-serving`. A generation receipt is a digest of the generated token +ids for local generation hooks. It does not show which model computed them. + +## How a receipt works + +1. The client names a VRF key in its request (`x-receipt-client-key`). +2. Each stage hashes the values of every layer while it serves the turn. + At the end of the turn, each stage commits those hashes with a BLAKE3 + Merkle root. +3. Stage 0 binds the roots, the tokens of the turn and the client key into + a turn root. It signs the turn root with its node key. This signed + record is the receipt, and it is in the response. +4. The VRF of the turn root draws the challenge: four layers, four + positions in each layer, and four sampled tokens. The client and the + node cannot choose them. +5. Each stage replays its part of the turn in a scratch context and opens + the challenged values. The node signs this opening. +6. The client checks the opening against the receipt and against the + claimed GGUF, on its own CPU. + +A node that serves a different quantization, or a different model, fails +these checks. + +## Outcomes and exit codes + +`skippy audit-receipt` and `skippy recheck-receipt` end with one of four +outcomes. The last line of the text report is the outcome. + +| Last line | Exit code | JSON `outcome` | Meaning | +|---|---|---|---| +| `AUDIT PASS` | 0 | `pass` | Every check ran and passed | +| `AUDIT FAIL` | 1 | `fail` | The receipt or the answer of the node is defective, or it contradicts what the client sent or received | +| `NO AUDIT` | 2 | `no_audit` | This machine could not run the audit. This says nothing about the node | +| `NO ANSWER` | 3 | `unanswered` | The node gave no usable signed answer to the challenge or to the request for rows | + +Each failure is one of two types: + +- A provable failure is in something that the node signed. `skippy + recheck-receipt` fails the evidence in the same way, on all machines. +- A failure that this client alone saw has the mark `(seen by this client + alone)` in the report. The response text and the request are of this + type. The node did not sign them, so they convince nobody else. When the + head key refuses the logits of a node, the audit also checks them on + every row of the output matrix, as `skippy recheck-receipt` does, and + reports that verdict. Only when that check cannot run here are logits + that the key alone refused of this type. A token that the opened logits + refuse is a provable failure, whatever the key found. + +A command error that is not an outcome, for example an evidence file that +cannot be written, also exits with 1. Read the last line of the report to +tell the two apart. + +## What a pass proves + +A pass is a statement about the picked layers, positions and sampled +tokens of one turn. For those, a pass shows that: + +- the node used the claimed weights, with the claimed quantization, in + every weight matmul of the four picked layers. +- the operations between the matmuls are those of the claimed model. +- the input of layer 0 is the embedding of the token that the receipt + names. +- at four sampled positions, the logits come from the claimed output + matrix, and the sampled token is one that the stated sampler can give. +- the response is the text of the tokens that the receipt names. +- at two positions per picked layer, the attention of one head agrees with + the committed K and V rows, within loose tolerances. +- when the turn continued a cached prefix, the same things hold at two + positions of the prefix, except the check of the sampled token. +- the message that the client passed ends in the prompt tokens of the + turn, or ends the cached prefix when the turn holds only the template + text after it. The system prompt and the history are not compared. + +A pass does not show these things: + +- The positions and layers that the challenge did not pick. The check is a + sample. +- Most of a cached prefix. The challenge picks two of its positions. A + node that changed one token of a long prefix is caught with a small + probability. +- A sampling draw near a boundary. The audit replays the draw of a sampled + turn within the draw band, 0.01% of the root mean square of the logits. + A node can steer a draw only when its uniform is that close to the + boundary between two tokens. +- The end tag of a reasoning budget. The audit replays which tokens the + budget forced, with the tags that the node states. It does not derive + the tags from the chat template. The report shows them. +- A seed that the node chose. When the request fixed no seed, the replay + shows only that the node followed the seed that it states. +- Exact attention. A change within the tolerances passes. +- The file hash. The audit reads the bytes that Hugging Face serves for + the named commit over TLS. +- Privacy. The node reads the prompt and the response. + +The full list, with the threat model, is in +[What a pass proves](design/RECEIPTS.md#what-a-pass-proves). + +## Requirements + +**Serving.** + +- Standalone Skippy issues receipts on binary split serving + (`skippy serve --stage-transport binary`). A Mesh node issues them for + the models that it serves alone and for the splits that it coordinates, + when `[receipts] enabled` is on. +- The weights are F32, Q8_0, Q4_0, Q5_0, IQ4_NL, IQ4_XS or a K-quant + from Q2_K to Q6_K on the CPU or CUDA, or F16 or BF16 on the CPU. Dense + and MoE models are supported. A stage whose weights have another type + for its backend, for example F16 or BF16 on CUDA, or Q4_1 anywhere, + issues no receipts. It serves normally, and `skippy serve` prints the + same warning as for a backend without profiles, with the type and the + tensor. The stage reads the types from the tensor directory of its + GGUF files when it starts. It checks the matrices of its own layers + and, on the last stage, the output head. CUDA sums F16 products in + half precision, which no profile models: an honest CUDA node with F16 + weights failed every audit. BF16 was never measured on CUDA. +- The backend is the CPU or CUDA. A stage on another backend (Vulkan, + Metal or ROCm) issues no receipts: its recorder does not start, the + stage serves normally, and `skippy serve` prints one warning, + `Receipts stay off for this model stage`, with the reason. The auditor + has no rounding profiles for those backends, so a receipt that names + one gets no audit. The CPU runtime for macOS uses the Accelerate + BLAS, which is such a backend, so no stage on macOS issues receipts. + A Mesh node does not advertise receipts for a runtime on such a + backend. Vulkan lost its profiles on 2026-11-10: an + honest Vulkan node with Q4_K_M weights on an integrated GPU passed 2 of + 16 audits. +- Every matrix product of the stage runs on one backend. A stage that + offloads only some of its layers issues no receipts, with the same + warning. llama.cpp counts the output layer as one more layer and + offloads from the end of the model, so `--n-gpu-layers` covers a stage + that starts at layer `s` of a model with `n` layers when it is at + least `n + 1 - s`, or -1. For Qwen3-4B (36 layers), the first stage + needs 37, and 99 or -1 cover any stage. +- A stage with no layer offloaded (`--n-gpu-layers 0`, or the CPU as its + selected device) in a runtime that has a GPU issues no receipts unless + op offload is off (`--op-offload=false`, or `op_offload = false` in the + stage config). With op offload on, which is the default, llama.cpp + runs the matrix products of every batch of 32 tokens or more on the + GPU, so the stage prefills on the GPU and decodes on the CPU. An honest + Qwen3-4B Q8_0 stage that way measured errors of about 1/3,000 in + every weight against the CPU profiles. With op offload off, the errors + were about 1/2,500,000, as on a runtime without a GPU, and the stage + issues receipts that name the CPU. +- The model uses flash attention. A stage with a transposed V cache gets + no receipt. +- The KV cache stores f16 rows, which is the default. A stage with a + quantized KV cache (`cache_type_k` or `cache_type_v` of q8_0 or q4_0) + issues no receipts, and a Mesh node does not advertise receipts for it. + A layer package can name a quantized cache as its default. Set both + cache types to f16 to get receipts. +- The KV cache can be unified, or it can keep one stream per sequence. +- The receipt classifier must accept the graph. See + [Troubleshooting](#a-turn-gets-no-receipt) for the reasons that it can + give. + +**Stages that issue receipts with a limit.** + +- A stage with a native MTP head issues receipts. The trunk checks every + draft, so the receipt covers the trunk and not the head. +- A hybrid model, for example Qwen3.5, issues receipts. See + [Hybrid memory](#hybrid-memory). +- On a hybrid stage, a turn that continues a cached prefix gets no + receipt. `skippy serve` issues receipts for the other turns. A Mesh + node does not advertise receipts for a hybrid model, because in Mesh a + peer that advertises receipts owes one for every turn, and each later + turn of a chat continues a cached prefix. +- A turn that continues a cached prefix gets no receipt when the stage + cannot replay a position of the prefix. See + [The cached prefix](#the-cached-prefix). +- A turn with image tokens gets no receipt. +- A model that has recurrent memory and no attention issues no receipts. A + standalone stage with such a model stops at startup when receipts are + on. + +**Auditing.** + +- The auditor needs the GGUF that the node claims: a local file, or a file + on Hugging Face that it reads by range. +- The auditor loads layer 0 and each challenged layer on the CPU, with the + native Skippy runtime. +- The auditor and the node must run the same Skippy ABI and the same + llama.cpp build. See [Upgrade and compatibility](#upgrade-and-compatibility). + +## Quick start + +This procedure serves a two-stage split on one machine and audits one +turn. + +1. Make the stage configs. The `--worker` addresses are the internal stage + listeners. The output directory must not exist. + + ```bash + skippy plan-split --model-path /models/Qwen3-4B-Q8_0.gguf \ + --worker 127.0.0.1:9400 --worker 127.0.0.1:9401 --output-dir plan + ``` + +2. Start stage 1 in one terminal. `--receipts` turns receipts on without a + receipts API. + + ```bash + skippy serve --stage-transport binary --worker-only \ + --config plan/stage-1.json --receipts + ``` + +3. Start stage 0 in a second terminal. `--receipts-listen` turns receipts + on and serves the receipts API. + + ```bash + skippy serve --stage-transport binary --config plan/stage-0.json \ + --bind-addr 127.0.0.1:9337 --receipts-listen 127.0.0.1:9501 + ``` + +4. Audit one turn. Against standalone `skippy serve`, `--receipts` is + necessary, because only a Mesh node opens receipts on its OpenAI + address. + + ```bash + skippy audit-receipt \ + --api http://127.0.0.1:9337 \ + --receipts http://127.0.0.1:9501 \ + --claimed-model /models/Qwen3-4B-Q8_0.gguf \ + --evidence evidence.json + ``` + +5. Read the last line of the report. `AUDIT PASS` and exit code 0 show + that the audit passed. + +6. Check the evidence again. This step needs only the evidence file and + the claimed GGUF. + + ```bash + skippy recheck-receipt \ + --evidence evidence.json \ + --claimed-model /models/Qwen3-4B-Q8_0.gguf + ``` + +## Serve with receipts + +Start stage 0 with `--receipts-listen`, which serves the receipts API that +clients and auditors use. Start each later stage with `--receipts`. Each +stage reaches the receipts of the next stage over the binary stage +connection. That connection is a dedicated one to the binary address of +the next stage. It carries only receipts messages and holds no lane. + +A later stage can also serve its own receipts API with `--receipts-listen`. +If you start the stage before it with `--receipts-downstream URL`, that +stage uses the API and not the stage connection. + +| Flag | Purpose | +|---|---| +| `--receipts` | Turn receipts on without a receipts API. Use it on a later stage | +| `--receipts-listen ADDR` | Turn receipts on and serve the receipts API on `ADDR` | +| `--receipts-allow-remote` | Permit a `--receipts-listen` address that is not loopback | +| `--receipts-downstream URL` | The receipts API of the next stage. Commits and openings for its layers go there | +| `--receipts-claimed-model NAME` | The model that each receipt names. The default is the stage model id | +| `--receipts-signing-key FILE` | A file with the Ed25519 seed that signs turn roots, as 64 hex digits. Without it, the stage makes a key at startup | + +Use `--receipts` or `--receipts-listen`, not both. The other four flags +need one of them. + +When receipts are on, the stage log has the line `receipts on:` with the +API address, the stage index and the layers. The stage also logs the node +key that signs its receipts. + +### Bound and unbound receipts + +A request gets a bound receipt when it names the VRF key of the client in +the `x-receipt-client-key` header (64 hex digits). Stage 0 binds these +things into the turn root and signs it: + +- the client key. +- the parent turn root, if the request names one in `x-receipt-parent`. +- the sampler statement, with the seed. A sampled turn draws with the seed + of the request body, else with the seed that the request names in + `x-receipt-seed` (a decimal number above 0), else with a random seed. +- the runtime: the `skippy-abi` version, the llama.cpp commit and a hash + of the patch queue. +- the sampler statement. +- its node key, and every field of the receipt. + +The sampler statement is `greedy` when every token was the best logit. +That is true with sampling off, or with temperature 0 and no penalties, +logit biases, grammar or reasoning budget. Otherwise the statement is +`sampled` and a JSON object with the parameters and the seed of the +sampler. A thinking model gets a default reasoning budget from the server. +So a request with temperature 0 gets a `sampled` statement unless it also +sends `"reasoning_budget": -1`. + +A turn with a reasoning budget states the budget, and what the runtime +built the sampler of the budget from, in the `reasoning` field: the tag +that starts the reasoning, the tags that end it, and the text that the +chat template placed after the prompt. For a model that reasons between +`` and ``, the two fields look like this example: + +```json +"reasoning_budget": 512, +"reasoning": { + "start": "", + "ends": [""], + "prefill": "<|im_start|>assistant\n" +} +``` + +The sampler forces the end tag when the reasoning uses the budget up. An +auditor replays the sampler from these texts and the tokens of the turn, +so it knows which tokens were forced. The rule is in +[Reasoning budget](design/RECEIPTS.md#reasoning-budget). + +The runtime builds that sampler for every chat with a finite budget whose +template names both tags and did not close the reasoning block itself. A +chat with no finite budget, or with reasoning turned off, has +`"reasoning": null` in its statement. The audit then judges every token +of the turn by the usual rule. + +A sampled turn that gets a receipt draws each token by the rule +`indexed-v1`, and the statement names the rule in `draw`. The uniform of a +token is a function of the seed and of the position of the token, and the +sampler takes the kept candidates in token id order. So a client that +knows the seed and the logits can replay the draw. A turn without a +receipt keeps the `dist` sampler of llama.cpp. The rule is in +[Sampling draw](design/RECEIPTS.md#sampling-draw). + +A bound receipt is in the response: in the `receipt` field of a chat or +text completion body, and of the last chunk of a stream. + +A request without a client key gets an unbound receipt on a split. An +unbound receipt is only on the receipts API, and the auditor rejects it. A +single stage in a Mesh node commits only bound turns. + +The recorder runs on every ubatch while receipts are on, for bound and +unbound requests. + +No shipped client keeps the chain of parent turn roots. The node binds the +parent that the client names and does not check it. + +### Keep the receipts API private + +The receipts API refuses an address that is not loopback unless you also +pass `--receipts-allow-remote`. + +CAUTION: Do not expose the receipts API to parties that must not read the +prompts. An opening contains activations that come from the prompt. + +A bound receipt opens only for the client that holds its VRF key. An +unbound receipt opens for all callers of the receipts API. + +### What a stage keeps + +A stage keeps leaf hashes and a replay log. It does not keep activations. + +- Per position, the stage keeps `2 · layers + 1` hashes and the Merkle + tree above them. +- Per ubatch, the log holds the tokens, the positions, the output rows, + the KV cells and `n_kv`. On a stage after the first, it also holds the + stage input rows: one hidden-state row per token. +- Committed turns, with the logs of turns not yet committed, use at most + 1 GiB per stage. The stage removes only turns that a client can no + longer challenge, the oldest first. When the turns that a client can + still challenge fill the 1 GiB, a new turn gets no receipt. +- The pinned cells of the bound turns of one client key hold at most half + of a KV stream, and all pinned cells at most three quarters. A new + bound turn always gets its pin and its receipt. Past a share, the + oldest pins give way, those of unchallenged turns first. A turn that + lost its pin can be opened until a later request writes its cells. +- A bound receipt is kept for the 12-second challenge pin, and for 30 + seconds after it is opened. +- The stage keeps at most 256 receipts that no client can still challenge, + and at most 64 MiB of receipts. It removes the oldest of them first. +- When the receipts that can still be challenged fill the 64 MiB, a new + turn gets no receipt. +- If a new turn uses a receipt id again, it replaces the record of the old + turn. It does not while the old turn can still be challenged and the + turn is bound: neither for another client, nor for the same client key. + A client keeps the receipt that it was signed while it can challenge it. + Then the new turn gets no receipt. + +A replay runs only the turn, on top of the KV cells that the turn read. +The receipt binds those cells by a prefix root, and an opening copies them +from the live cache. So an opening fails after another request wrote one +of those cells. + +### The cached prefix + +A challenge also picks two positions of the cached prefix. The stage did +not compute them in the turn. For every KV cell it keeps the leaf hashes +of the position and the recorded ubatch that wrote the cell. It opens a +picked position by a replay of that one ubatch, on top of the cells below +it. Another request, or a cache sequence, may have computed the prefix. +The stage that holds layer 0 sends the tokens of the whole prefix with the +opening, and the receipt binds their digest. + +What this costs an operator: + +- Memory. The leaf hashes are about 2.3 kB per position for a stage of 36 + layers, less than 2% of the K and V rows. A stage after the first also + keeps the input rows of each ubatch, at most 1 GiB. Past that it drops + the oldest ubatch. +- Time. An opening of a cached turn also replays up to two ubatches of the + prefix. On a CPU stage that can take seconds for a ubatch of 512 tokens. + The time is not measured yet. + +A turn gets no receipt when the stage cannot replay its prefix: + +- after a state load, a context shift or a compaction; +- when a ubatch that the recorder could not record wrote a cell of the + prefix; +- when the prefix holds cells of two requests; +- when the ubatch of a prefix cell is past the 1 GiB of input rows; +- on a stage with recurrent state. + +The log line names the cause after `the turn's cached prefix is unknown`. + +Each stage pins the cells of a bound turn for its challenge window of 10 +minutes, so a later request writes other cells while the cache has room. +The pin is firm for the first 12 seconds. After that the turn lingers: +lingering turns pin a quarter of a stream at most, and the oldest lose +their pin past that. A turn that lost its pin can still be opened until a +request writes its cells. When a challenge +arrives, the stage pins the turn again until the opening ends, for at +most 20 seconds, because the opening reads the cells after the replay. +After the opening, the pin stays until the client has its rows, for at +most 30 seconds. A stage with a full cache writes pinned cells anyway, +and the turn can then no longer be opened. An unbound turn is not +pinned. + +With receipts on, a repeated greedy request does not reuse the tokens that +an earlier request generated. The turn computes them again. + +With receipts on, a stage of a split takes a cached prefix of a prompt +only when stage 0 restores it on every stage. No stage restores the first +chunk of a prompt from its own cache, so all stages start a turn at the +same position and commit the same positions. + +### Hybrid memory + +A recurrent layer (Mamba, the gated delta net) keeps one state per +sequence, and each ubatch writes over it. A replay cannot build that state +again from the KV cache. + +- Before the first ubatch of a turn, the stage reads the state from its + recurrent memory. +- The stage commitment names the BLAKE3 digest of the state in + `recurrent_state`. +- The stage keeps the state while a client can challenge the turn. A + replay starts from that state. +- Each ubatch also commits the state that it read, in the mixing leaf of + its first position. + +For the first attention pick of a stage on a recurrent layer, the auditor +runs the token-mixing ops of the layer again on the CPU. It compares the +outputs and the states at both ends of the opened region. + +A hybrid stage restores a cached prefix with a KV page import and a state +read. The recorder cannot replay those, so a turn that continues a cached +prefix gets no receipt on a hybrid stage. For that reason a Mesh node +does not advertise receipts for a hybrid model, and says so in a warning +when `[receipts] enabled` is on. + +## Audit a response + +`skippy audit-receipt` makes a new VRF key and sends one chat request that +names it. It gets the receipt, draws the challenge from the VRF of the +turn root, and checks the opening. + +```bash +skippy audit-receipt \ + --api http://127.0.0.1:9337 \ + --receipts http://127.0.0.1:9501 \ + --claimed-model /models/Qwen3-4B-Q8_0.gguf +``` + +| Flag | Default | Purpose | +|---|---|---| +| `--api URL` | `http://127.0.0.1:9337` | The OpenAI base URL of stage 0 | +| `--receipts URL` | None | The receipts API of stage 0. Without it, the command opens the receipt on the OpenAI API, which only a Mesh node serves | +| `--claimed-model MODEL` | Required | The GGUF that the node claims: a local file, or `repo@revision/file` on Hugging Face | +| `--model ID` | The first model that the node lists | The model id that the chat request names. A Mesh node lists its router `mesh` first, so name the served model for a Mesh node | +| `--prompt TEXT` | `Explain in two sentences why the sky is blue.` | The prompt of the request | +| `--max-tokens N` | 32 | The response length | +| `--layer N` | None | Challenge this layer alone. The report then says that the challenge is not evidence | +| `--timing-runs N` | 1 | Compute each challenged layer N times for the cost report | +| `--evidence FILE` | None | Write the evidence of the audit to this file. You cannot use it with `--layer` | +| `--temperature T` | 0 | Sample at this temperature. At 0 the node decodes greedily. Above 0 the audit sets a seed and replays the draw of each checked token | +| `--top-p P` | The default of the node | Top-p of a sampled turn. Needs `--temperature` | +| `--top-k K` | The default of the node | Top-k of a sampled turn. Needs `--temperature` | +| `--min-p P` | The default of the node | Min-p of a sampled turn. Needs `--temperature` | +| `--seed N` | Random | The seed of a sampled turn, above 0. Needs `--temperature` | +| `--reasoning-budget N` | No limit | The reasoning tokens that the request allows a thinking model. Where the runtime enforces the budget, the node forces the end of the reasoning when they run out, and the audit replays which tokens it forced | +| `--output json` | Text | Print the report as JSON | + +The command sends the request to the first model that `GET /v1/models` +lists. It asks for greedy decoding: temperature 0 and +`"reasoning_budget": -1`. With `--reasoning-budget N` it sends that +budget instead, and the statement of the node is then `sampled` also at +temperature 0. + +Without `--receipts`, the command takes the receipt from the response and +opens it with `POST /v1/receipts/open` on the OpenAI address. The challenge +names the model, and it names the node key of the receipt in +`x-mesh-target`. A Mesh node thus sends the challenge to the peer that +signed the receipt. + +### The claimed model + +`--claimed-model` takes a local GGUF or a Hugging Face file as +`repo@revision/file`, for example +`unsloth/Qwen3-4B-GGUF@main/Qwen3-4B-Q8_0.gguf`. Name a split GGUF by its +first shard. The command reads every shard. + +The command does not download a Hugging Face file. It reads only the bytes +that the checks use, with range requests, into a sparse copy. Those bytes +are the header, the small tensors of the challenged layers, the checked +rows, the embedding rows of the challenged tokens, and the output matrix. + +- The sparse copy is in the platform cache directory, at + `~/.cache/mesh-llm/receipts/claimed/` on Linux. It is keyed by the commit + that the revision resolves to. Without a cache directory (no `HOME` and + no platform cache directory), the result is `NO AUDIT`. The command never + keeps the copy in the shared temporary directory. +- Later audits fetch only the bytes that the copy does not hold. +- The copies keep at most 8 GiB. Opening a copy removes the copies that + were used longest ago until the rest fit. A copy that another audit has + open stays. +- One audit fetches at most 3 GiB, the header included. A model over that + gives `NO AUDIT`. +- Each range answer must be for the bytes that the command asked for + (`Content-Range`), and the command reads no more than it asked for. +- The output matrix is read one time, to build the head key. The copy does + not keep it. +- `HF_ENDPOINT` and `HF_TOKEN` apply. The token goes only to the Hugging + Face host, not to the CDN. +- The header is read before the request, so it does not delay the + challenge. + +The command reads the GGUF header strictly, for a local file too. It +refuses a file over its limits, and the result is then `NO AUDIT`. The +limits are in [Parameters](design/RECEIPTS.md#parameters). + +Before llama.cpp loads the model, the command checks the metadata values +on which the llama.cpp loader and tokenizer stop the process: the layer, +expert and head counts, RoPE, pooling, the context length, the epsilon +values and the vocabulary. A model that fails gives `NO AUDIT`. A layer +that reads the KV cache of another layer, as in Gemma 3n and Gemma 4, +also gives `NO AUDIT`. These checks do not cover every path of llama.cpp. +See [Open limitations](design/RECEIPTS.md#open-limitations), +item 19. + +The command trusts the revision in `--claimed-model`, a branch included. +A commit of a branch does not by itself show that the owner published it: +Hugging Face also serves the commits of pull requests, which anyone can +open. Name the branch, or a commit that you checked, and not a commit from +someone else. + +### The checks, in order + +Before the challenge, the command decides from the receipt alone whether +this machine can audit it. See [NO AUDIT](#no-audit). Then it does these +checks: + +1. **Receipt.** The receipt is bound to the key of the auditor. The turn + root matches the fields, and the signature of the node key is correct. + The stages cover every layer of the claimed GGUF from 0, in order. The + layer count comes from the metadata of the GGUF, not from the receipt. +2. **Request.** The receipt has the id of the request, and the sampler + statement does not contradict the request. Without `--temperature` + and `--reasoning-budget`, `audit-receipt` asks for greedy decoding, so + a receipt whose sampler is not `greedy` fails. With them, the statement + must name the temperature, the filters, the seed and the reasoning + budget of the request, with their exact values. A filter that the + request left out must not be stated off. A sampled turn must name the + `indexed-v1` draw. The statement may not name `ignore_eos`, a grammar, + a penalty, another sampler or a `reasoning` sampler that the request + did not ask for. A statement whose fields do not have the types that + an honest node writes fails check 1, and the evidence shows it. +3. **Opening.** The signature of the node covers the bytes of the opening + and the challenge that it answers. The opening holds exactly the stages, + layers and positions of the challenge, with nothing twice and nothing + extra. Every opened leaf is in the tree of its stage. Where one stage + hands over to the next, both stages open the same residual leaf. A + picked position of a cached prefix is in no tree of the turn. The stage + opens every leaf hash that it committed for the position, and those + must be in the prefix tree of the receipt. The tokens of the prefix + must hash to the digest in the receipt. +4. **Values.** Every opened value is finite and has the length that the + claimed GGUF gives. The checks below read only values that passed + checks 3 and 4. +5. **Weight rows.** For each matmul of a picked layer, the command reads 16 + random rows of the weight from the claimed GGUF and computes them again. + The rows come from the VRF of the bytes of the opening. Each matrix is + checked with the rounding profiles of the backend that its stage names. + A router is checked on every row. +6. **Glue.** The command builds each picked layer with its own llama.cpp + from the claimed GGUF, and computes it on the opened values. First it + computes the layer from the committed values alone, and compares the + opened matmuls, mixing values and selections with the layer it built. + A value that the layer does not take then fails the node, not this + machine. See + [What the glue checks bind](#what-the-glue-checks-bind). +7. **Input of layer 0.** The command computes the input of layer 0 from + each token in the receipt, with layer 0 of the claimed GGUF. The result + must be the opened input at every picked position. +8. **Output head.** The challenge names four positions from which the turn + sampled a token. At each, the final stage opens the residual that leaves + the last layer and the logits of its replay. The command checks the + logits with its secret head key. It also checks 16 random rows of the + output matrix and the row of the sampled token. Then it checks that the + sampled token is the greedy choice. The model's suppressed tokens, and + for a turn with `ignore_eos` its end-of-generation tokens, are out of + the candidates first, as the runtime takes them out. +9. **Attention.** At two positions per picked layer, the node opens the + attention of one head as partial sums over blocks of 64 context + positions. The partials must combine to the committed attention output. + The tolerance is 2e-2 for a head that attends to at most about 420 + positions. For more positions it increases with the square root of the + context: 6.3e-2 at 4,096 positions and 1.8e-1 at 32,768. The sum of + each block must be between 1 and the number of positions in the block. + Then the command draws two blocks per pick, the first in proportion to + its weight in the combination and the second uniformly, and asks for + their K and V rows (`POST /receipts/rows`). It computes those blocks + again from the committed q, within 1e-6. +10. **Response.** The response (reasoning and content together) is the text + of the sampled tokens, up to whitespace and reasoning markers. An empty + response fails. A response that the node cut at the token limit must be + the start of that text. It can leave out only an unfinished character + or the start of a marker. The message that the client passed must end + in the prompt tokens of the turn. When the cached prefix holds all of + the prompt but its last token, the message must end the prefix, with + at most 128 characters of template text after it. + +Notes on the checks: + +- A column that fails check 5 is repaired when an activation near-tie + explains it. The report counts repaired columns (`repaired_tokens` in + JSON). The rule is in + [Fail rule](design/RECEIPTS.md#fail-rule). +- In check 8, the tie band is 1% of the root mean square of the logits. A + token whose logit is inside the tie band of the best logit is accepted + and counted as a tie. More than one tie in four positions is flagged, not + failed. +- In check 8, a sampled turn must take a token that its stated `top_k`, + `top_p`, `min_p` and temperature keep. A turn with penalties, DRY, XTC, + typical or top-n-sigma sampling, mirostat or a grammar gets no token + judgement. Its logits are still checked. An empty chain is the default + chain of the runtime, and a `top_p` of 0 keeps the best token, as in + llama.cpp. +- In check 8, the audit replays the draw of a sampled turn whose statement + names the `indexed-v1` rule. The report shows how many draws pick the + sampled token, and how many do so only within the draw band. The draw + band is 0.01% of the root mean square of the logits that the node + opened. More than one such draw in four positions is flagged, not + failed. A draw that does not pick the sampled token fails the audit, and + the evidence shows it. The replay follows the f32 arithmetic of the + runtime's filters. A turn with a dynamic temperature gets no replay. A + turn at temperature 0, or with a `top_k` of 1, draws nothing. +- In check 8, the audit replays the reasoning budget of a turn that states + one. A token that the budget forced must be the forced token: the end + tag of the reasoning, one token at a time. Every other token is judged + as usual. The report has a line `reasoning budget of N tokens, from + ... to ... as the node states them: forced M of the checked tokens`, + and the JSON report has the stated tags in `head.verdict.reasoning` and + the forced token of a position in `forced`. The tags are the statement + of the node. Compare them with the chat template of the model if you + know it. A statement with a tag of more than 256 bytes, more than 8 end + tags or a prefill of more than 1,024 bytes leaves the tokens unjudged, + and so does a prefill that is not the end of the prompt. The runtime + builds the sampler only for a turn with a grammar, so the audit refuses + a `reasoning` sampler on a turn without one as a contradiction. A + recheck has no request and replays it. +- When the request set no seed, the report has a note: the draws were + replayed with the seed that the node chose. +- The head key is a file that only its owner can read. It has 16 secret + sign vectors, so two logit changes that cancel go unseen 1 in 65,536 + times. A key file of an older version is built again. The report shows + whether the key accepted the logits and how far from its tolerance they + were in powers of ten, never the key's error. When a check with the key + refuses the logits of a node, the command deletes the key, and the next + audit builds a new one. If the node opens no logits, that is a + failure of the node, in the audit and in a recheck. +- In check 9, a layer whose attention the check cannot follow gives a + `could not check:` line. If nothing failed, the outcome is then + `NO AUDIT`. That says nothing about the node. +- When a turn continues a cached prefix, the challenge picks two positions + of the prefix in every picked layer, and the prompt check reads the + tokens of the prefix and of the turn. The report line says where the + message was found, after a cached prefix of N positions. + +### A pass + +This report is from an audit on 2026-11-09. The node is honest and serves +the claimed Q8_0 GGUF, with both stages on the CPU. Lines with `...` are +removed lines. + +```text +response: The harbor at dawn is a quiet, golden-hued sanctuary where the first light of day paints the water in soft hues + +receipt 2481a665-206d-436e-8d38-9038fed18da0 model Qwen3-4B-Q8_0 positions 0..44 generation from 21 + stage 0 layers 0..18 root ddc64b2f324d2ac6… leaves 1628 cache f16 (CPU) + stage 1 layers 18..36 root d7cea91ab4fae165… leaves 1628 cache f16 (CPU) + turn root 9a641adc549e561c… node key 4ea448670cd034ae… client key 5177fa51677edb4d… skippy-abi 0.1.81; llama.cpp 372dc5ca157276beb6c67b2e92477e8d662e964a patches 22c4606fa8d1400aca80e531baad6424d83af05e0daab3b033dd7b5b03615d99 sampler greedy +challenge: layer 17 (stage 0), positions [12, 20, 39, 40] +challenge: layer 22 (stage 1), positions [7, 13, 28, 35] +challenge: layer 23 (stage 1), positions [6, 20, 25, 42] +challenge: layer 28 (stage 1), positions [1, 14, 24, 40] +opening: 1.02 s +receipt binding and signature, shape, opening form, merkle paths, stage boundaries and values: ok +layer 17: + blk.17.attn_k.weight q8_0 4/4 pass max err 1.4e-7 cpu_q8_0 + blk.17.attn_output.weight q8_0 4/4 pass max err 2.5e-7 cpu_q8_0 + ... + blk.17.ffn_up.weight q8_0 4/4 pass max err 1.8e-7 cpu_q8_0 + glue matmul inputs 28/28 pass max err 0.0e0 ok + glue mixing inputs 4/4 pass max err 0.0e0 ok + glue stored rows 8/8 pass max err 0.0e0 ok + glue residual out 4/4 pass max err 0.0e0 ok + client cost: layer load 0.39 s, glue 6.55 ms per position (4 positions, first run 26 ms), row checks 4 ms +layer 22: + ... +weight rows, each role across the opened layers: + attn_k.weight 16/16 pass ok + attn_output.weight 16/16 pass ok + ... + ffn_up.weight 16/16 pass ok +input of layer 0 from the receipt's tokens: 14/14 pass max err 0.0e0 ok +sampled tokens at [24, 27, 28, 35] are the greedy choice: 4/4 pass ties 0 ok (0.02 s, node's logits checked with the head key) +attention, per picked head: + position 20 layer 17 head 2 21 positions combine 3.5e-4 blocks [0] 2.2e-8 ok + position 40 layer 17 head 22 41 positions combine 6.1e-4 blocks [0] 2.9e-8 ok + ... + position 40 layer 28 head 13 41 positions combine 1.6e-4 blocks [0] 2.8e-8 ok + rows opened in 0.01 s +response is the text of the sampled tokens: ok +prompt is in the receipt's tokens: ok +AUDIT PASS +``` + +A MoE layer adds lines for the router, which is checked on every row, for +the expert ids, and for the selections. + +### A failure + +This report is from 2026-11-09. The node serves another quantization of +Qwen3-4B on the CPU, and its receipts claim Q8_0. + +```text +challenge: layer 14 (stage 0), positions [7, 9, 25, 28] +challenge: layer 16 (stage 0), positions [4, 10, 32, 33] +challenge: layer 23 (stage 1), positions [11, 18, 35, 37] +challenge: layer 27 (stage 1), positions [2, 5, 28, 37] +opening: 0.76 s +receipt binding and signature, shape, opening form, merkle paths, stage boundaries and values: ok +layer 14: + blk.14.attn_k.weight q8_0 0/4 pass max err 4.3e-2 cpu_q8_0 + ... + glue matmul inputs 28/28 pass max err 0.0e0 ok + glue mixing inputs 4/4 pass max err 0.0e0 ok + glue stored rows 8/8 pass max err 0.0e0 ok + glue residual out 4/4 pass max err 0.0e0 ok + ... +weight rows, each role across the opened layers: + attn_k.weight 0/16 pass FAIL + ... + ffn_up.weight 0/16 pass FAIL +input of layer 0 from the receipt's tokens: 0/14 pass max err 1.9e-2 FAIL +sampled tokens at [25, 28, 34, 35] are the greedy choice: 0/4 pass ties 0 FAIL (0.03 s, node's logits checked with the head key) + position 25: key error 4.228e-2, row error 1.445e-2 + ... + position 25: sampled 264, best 264, margin 4.010e0 (band 4.134e-2) + ... +attention, per picked head: + position 25 layer 14 head 30 26 positions combine 1.8e-4 blocks [0] 3.8e-8 ok + ... + rows opened in 0.01 s +response is the text of the sampled tokens: ok +prompt is in the receipt's tokens: ok +failed: weight rows of attn_k.weight: 16/16 fail, 16 past the cap +failed: weight rows of attn_output.weight: 16/16 fail, 16 past the cap +... +failed: weight rows of ffn_up.weight: 16/16 fail, 16 past the cap +failed: input of layer 0 +failed: output head (seen by this client alone) +AUDIT FAIL +``` + +The Merkle paths, the glue checks and the attention check pass. The node +committed to what it computed, and its replay gave the same values. The +weight rows fail because those values do not come from the claimed +weights. The input of layer 0 fails because the token embeddings are not +the claimed Q8_0 ones. The output head fails against the head key of this +client, which nobody else has, so it has the mark `(seen by this client +alone)`. A recheck shows the same failure without the key. + +Since 2026-11-11 a report differs in three places. When the head key +refuses the logits, the audit checks them again on every row of the +output matrix and reports that verdict, so the output head failure above +is provable and has no mark. A line for logits that the key checked says +whether the key accepted them and how far from its tolerance they were +in powers of ten, not `key error`. The prompt line says where the message +was found, for example `prompt message is where the turn read it: ok +(the message ends in the turn's own tokens; the system prompt and history +are not compared)`. + +The error line on standard error repeats the failures, after the native +log of the auditor: + +```text +error: the receipt audit failed: weight rows of attn_k.weight: 16/16 fail, 16 past the cap; ... +``` + +### NO AUDIT + +`NO AUDIT` means that this machine could not run the audit. It is not a +failure, and it says nothing about the node. A node whose receipts no +machine can audit gets no passes. + +This report is from a command with a `--claimed-model` that does not +exist: + +```text +receipt : the claimed model /nonexistent/model.gguf is neither a file here nor repo@revision/file on Hugging Face: it is not repo@revision/file +NO AUDIT +``` + +The command also writes this line to standard error and exits with 2: + +```text +error: the receipt was not audited: the claimed model /nonexistent/model.gguf is neither a file here nor repo@revision/file on Hugging Face: it is not repo@revision/file +``` + +See [Troubleshooting](#no-audit-causes) for the causes. + +### NO ANSWER + +`NO ANSWER` means that the node gave no usable signed answer. Nothing was +checked, and the cause is on the side of the node or of the network. + +This report is from a command whose `--receipts` address refuses +connections: + +```text +receipt 8e3c78ce-7f74-4792-a0e6-64a7d46122d5: the node did not answer /receipts/open: error sending request for url (http://127.0.0.1:9/receipts/open): client error (Connect): tcp connect error: Connection refused (os error 111) +NO ANSWER +``` + +The command also writes this line to standard error and exits with 3: + +```text +error: the node did not answer the audit: error sending request for url (http://127.0.0.1:9/receipts/open): client error (Connect): tcp connect error: Connection refused (os error 111) +``` + +See [Troubleshooting](#no-answer-causes) for the causes. + +### The JSON report + +Use `--output json` for a report that a program can read. Every report has +`outcome` and `pass`. This is a part of the report of a pass on +2026-11-09, with fields removed: + +```json +{ + "outcome": "pass", + "pass": true, + "failures": [], + "unchecked": [], + "notes": [], + "binding_error": null, + "receipt_error": null, + "opening_error": null, + "request_errors": [], + "anchors": { + "verdict": { "check": "anchors", "tokens": 13, "failing_tokens": 0, "max_error": 0.0, "pass": true } + }, + "tokens": { + "verdict": { "response_ok": true, "prompt_ok": true } + }, + "hand_picked": false, + "open_seconds": 0.958884305 +} +``` + +| Field | Content | +|---|---| +| `outcome` | `pass`, `fail`, `no_audit` or `unanswered` | +| `pass` | `true` only for the outcome `pass` | +| `failures` | A list of `{check, provable}`. `check` is the text of a `failed:` line. `provable` is `false` for a failure that this client alone saw | +| `unchecked` | The checks that could not run on this machine. These are the `could not check:` lines | +| `notes` | What the audit does not cover for this turn. These are the `note:` lines | +| `binding_error` | Why the receipt is not bound to this client or not signed | +| `receipt_error` | Why the signed receipt does not describe a turn of the claimed model | +| `opening_error` | Why the signed opening is defective | +| `request_errors` | How the receipt contradicts the request | +| `anchors`, `head`, `tokens` | Each is one of `{"verdict": ...}`, `{"node_fault": "..."}` or `{"unavailable": "..."}` | +| `tokens.verdict.prompt_ok` | Whether the message that the client passed ends in the prompt tokens of the turn, or ends the cached prefix when the turn holds only template text after it | +| `tokens.verdict.prompt_compared` | Where the message was found, in words. The system prompt and the history are not compared | +| `head.verdict.positions[].key_margin` | How far under the tolerance of the head key the logits were, in powers of ten; below 0 they were over it. The key's error is never shown | +| `head.verdict.positions[].token_ok` | Whether the token passed on the logits that the node opened | + +A `NO AUDIT` report has `outcome`, `pass`, `receipt_id` and `reason`. A +`NO ANSWER` report also has `request`, which is `open` or `rows`. + +The text report prints the `note:`, `failed:` and `could not check:` lines +immediately before the outcome line. It escapes each string that the node +chose and cuts it at 512 characters. + +### What the glue checks bind + +A replay computes the challenged layer again. So its matmuls pass the row +checks even if different weights served the turn. The glue check ties the +replayed matmuls to the committed values. The auditor builds the +challenged layer with its own llama.cpp from the claimed GGUF. It replaces +every weight matmul output, token-mixing output and selection with the +opened value, and the residual that enters the layer with the opened one. +Then it computes the layer and compares: + +- the input of each weight matmul, and the experts of each MoE matmul. +- each token-mixing input, such as q after RoPE. +- each stored KV row. The opened row is in the type of the cache. The + auditor rounds its own f32 value into the cache type and measures that + distance. The opened row can be no further from the f32 value than 1.5 + times that distance, plus 1e-4 of the norm of the row. +- each selection, against scores from the opened router output. A top-k + must hold the highest scores, and an argsort must be in order. +- the residual that leaves the layer. + +The node must also show that its replay gives every committed leaf of the +challenged positions. The glue check does not look inside attention or +another token-mixing op. Check 9 checks attention loosely. + +The glue tolerance is 1e-4, relative to the largest value of the reference +column. The row tolerance is 1e-3, relative to a scale that the command +computes from its own weights and the opened activation. A weight role +(`attn_q.weight`, `ffn_down_exps.weight`, and the others) is judged on its +columns in all opened layers together. A role fails when more than +`2 + n/32` of its `n` columns fail, which is 2 of 16, or when one column is +past 1e-2. A router of f32, f16 or bf16 weights fails on one failing +column. + +## Recheck evidence + +`--evidence FILE` makes `audit-receipt` write the evidence of the audit. It +writes the file for a pass and for a failure. The file holds: + +- the signed receipt. +- the challenge, with the VRF proof that drew it. +- the bytes of the opening, with the signature of the node. +- the VRF proof that drew the checked rows. +- the attention rows that the node sent after the opening, with their + signature. + +An audit that refuses the receipt sends no challenge and writes no +evidence. An audit with `--layer` writes none either. + +Anyone with the evidence and the claimed GGUF can check the audit again: + +```bash +skippy recheck-receipt \ + --evidence evidence.json \ + --claimed-model /models/Qwen3-4B-Q8_0.gguf +``` + +`--claimed-model` takes the same values as in `audit-receipt`. Without it, +the command reads the model that the receipt names. That works only when +the name is `repo@commit/file` on Hugging Face with a full commit. A Mesh +node names its model in that way when the GGUF came from Hugging Face. +The command then does not check that the commit is in the history of a +branch, and the report says so. The node chose the commit, and it can be +the commit of a pull request with other weights. To check against the +model that you expect, pass `--claimed-model` with the branch or a commit +that you trust. + +The command first makes sure that the file is evidence: + +- The node signed the receipt, the opening for this challenge, and the + rows. +- The VRF of the client key draws exactly this challenge from the turn + root, and these rows from the bytes of the opening. + +A file that fails this is not evidence, and the result is `NO AUDIT`. Then +the command does the checks of the audit again and ends with the same four +outcomes and exit codes. Three things differ from the audit: + +- The response is not part of the evidence, because the node does not sign + it. Check 10 does not run. +- The recheck has no head key. It reads the full output matrix and checks + the opened logits on every row, with the rounding of the backend of the + node. The tolerance is the tolerance of the head key, 1e-5 of the norm + of the logits. Then it judges the sampled token on the same logits. So + check 8 gives the result that it gave in the audit. An audit whose head + key refused the logits checks them on every row too, so the two agree. +- For a model that soft-caps its logits, the audit and the recheck do not + judge the tokens: logits that they compute lack the rounding of the + node, so a token of an honest node inside a near-tie could fail. They + check that the opened final residuals fit the output head. +- Evidence without attention rows reports the rows as missing. That is + `NO AUDIT`, not a failure. + +This report is the recheck of the evidence of the failure above, on +2026-11-09: + +```text +weight rows, each role across the opened layers: + attn_k.weight 0/16 pass FAIL + ... + ffn_up.weight 0/16 pass FAIL +input of layer 0 from the receipt's tokens: 0/14 pass max err 1.9e-2 FAIL +sampled tokens at [25, 28, 34, 35] are the greedy choice: 0/4 pass ties 0 FAIL (0.10 s, node's logits checked on every row of the output matrix) + ... +attention, per picked head: + ... + rows opened in 0.00 s +response: not part of the evidence (the node does not sign it) +failed: weight rows of attn_k.weight: 16/16 fail, 16 past the cap +... +failed: weight rows of ffn_up.weight: 16/16 fail, 16 past the cap +failed: input of layer 0 +failed: output head +AUDIT FAIL +``` + +## Receipts in Mesh + +A Mesh node serves receipts through its Skippy runtime and can audit the +turns that its peers serve. How to turn that on, how the node chooses the +turns it audits, how to read its verdicts and how to lift a block are in +the mesh-llm repository, in `mesh/docs/design/RECEIPTS.md` and +`mesh/docs/design/TRUST_TIERS.md`. + +## HTTP API + +A stage that you start with `--receipts-listen` serves these routes on its +receipts address. A stage that you start with `--receipts` alone serves no +HTTP API. + +| Route | Served by | Purpose | +|---|---|---| +| `GET /receipts/{id}` | Stage 0 | The receipt for a response. `id` is the receipt id of the request | +| `POST /receipts/open` | Each stage | Opens a challenge on this stage and on every later stage. Returns one opening per stage | +| `POST /receipts/rows` | Each stage | After an opening, returns the K and V rows of the attention blocks that the client drew, from this stage and every later stage | +| `POST /receipts/commit` | Stages after stage 0 | Commits the positions of a session. The stage before calls it at the end of a turn | + +The receipt id is the `x-receipt-id` of the request, when it holds exactly +one UUID. Mesh names a new one for each attempt. Without that header, the +receipt id is the `x-request-id` of the request: a client can send its own +UUID in that header, or read the `x-request-id` header of the response. A +node from before `x-receipt-id` ignores the header and uses the +`x-request-id`. Stage 0 commits a turn when its response ends. If +`GET /receipts/{id}` returns 404 immediately after the response, send the +request again. + +**Challenge body** (`POST /receipts/open`): + +```text +{ + "receipt_id": "...", + "picks": [{"layer": N, "positions": [...]}], + "head": [...], + "attention": [{"position": N, "layer": N, "head_draw": N}], + "proof": "" +} +``` + +A stage admits a challenge before it replays anything: + +- at most 4 layers, in increasing order. +- 1 to 4 increasing positions per layer, inside the turn. +- before them, at most 2 positions of the cached prefix, the same in every + layer. +- at most 4 head positions. +- at most 2 attention picks per layer, each at a picked position. + +A challenge outside these bounds gets HTTP 400. For example, a challenge +of 36 layers gets `the challenge picks 36 layers; a draw picks at most 4`. + +For a bound receipt, `proof` is necessary, and each stage opens one +challenge. An unbound receipt opens for at most 4 different challenges. + +**Rows body** (`POST /receipts/rows`): + +```text +{ + "receipt_id": "...", + "picks": [{"position": N, "layer": N, "blocks": [...]}], + "proof": "" +} +``` + +Each pick must be an attention pick of the admitted challenge, with at +most 2 blocks in increasing order. For a bound receipt, `proof` is +necessary. + +For a bound receipt, stage 0 signs the response body of both routes with +its node key, in the `x-receipt-opening-signature` header. + +**Commit body** (`POST /receipts/commit`): `receipt_id`, `session`, +`position_start`, `position_end`, and `client_key` for a bound turn. + +Between stages over HTTP, a forwarded open of a bound receipt has the +header `x-receipt-turn-root`. A forwarded rows request has the header +`x-receipt-opening-digest`. + +**Status codes** on `/receipts/open`, `/receipts/rows` and +`/v1/receipts/*`: + +| Status | Meaning | +|---|---| +| 200 | The answer | +| 400 | A refused or malformed request, and every case that is not below | +| 403 | The route opens only bound receipts, and this receipt is unbound | +| 404 | The stage keeps no record of the receipt id. The id is unknown, or the record was removed | +| 409 | The stage can no longer open the turn: `cells_overwritten`, `cells_unknown` or `state_dropped` | +| 410 | The turn left the opening window: `expired` | +| 503 | The stage was unloaded, or it is busy with other openings. A busy stage sends `Retry-After` | + +The body of an error is `{"error": "..."}`. The body of a 409 or a 410 also +has `cannot_open` with `receipt_id`, `stage_index`, `reason` and `detail`. +For a bound receipt, the node signs that body in the +`x-receipt-opening-signature` header. Stage 0 cuts the `detail` of a later +stage to 256 bytes and replaces its control characters. + +A stage works on one opening or rows request at a time. At most 8 others +wait, at most 2 of them of one client key, each for at most 8 seconds. +When several wait, the client key that used the stage least since it was +last idle goes next. A request past these limits gets 503 with +`Retry-After: 2` and `retry_after_secs` in the body. The node does not +sign this answer. The stage did not admit the challenge, so send it again +after the retry time. `skippy audit-receipt` and the Mesh auditor do +that for 10 seconds. A stage that is still busy then gave no answer. + +A stage reads rows for at most 4 rows requests of one receipt. It keeps +each answer, and answers the same request again from it, also after the +turn's cells were written. + +`GET /receipts/{id}` returns 404 when no receipt has that id, and 400 with +the reason when the turn got no receipt. For a bound receipt, it returns +the receipt without `tokens` and `final_token`, because the id is all that +the route asks for. The client of a bound turn gets the whole receipt in +the response. + +A program that embeds the runtime can serve receipts without a receipts +address. It then mounts two routes on its OpenAI address, for clients +that reach the node only there. A Mesh node does this. Standalone +`skippy serve` does not. + +| Route | Purpose | +|---|---| +| `POST /v1/receipts/open` | `POST /receipts/open` for a bound receipt. The body can also name the `model`, by which a Mesh node routes the request. An unbound receipt returns 403 | +| `POST /v1/receipts/rows` | `POST /receipts/rows` for a bound receipt, with the same `model` field | + +These routes open bound receipts only. So only the client reads the +activations of a turn. + +## Troubleshooting + +### A turn gets no receipt + +A stage that cannot issue a receipt for a turn serves the turn normally. +The response then has no `receipt` field. Find the reason in one of these +places: + +- the log of stage 0, in a warning that starts with `receipt not + committed:`. +- `GET /receipts/{id}`, which returns HTTP 400 with `turn got no + receipt:` and the reason. +- the report of `skippy audit-receipt --receipts URL`, which ends with + `NO AUDIT` and quotes that answer. + +| Reason contains | Cause | What to do | +|---|---|---| +| `the response carried no receipt` | Receipts are off on the node, or the turn got none, and the command has no `--receipts` | Start the stages with the receipts flags. Pass `--receipts` to the audit | +| `op ... is not in the receipt op table` | The graph uses a ggml op that the classifier does not know | Serve this model without receipts. Report the op | +| `the V cache is stored transposed; receipts need flash attention` | Flash attention is off | Turn flash attention on | +| `no audit covers a quantized KV cache` | A KV cache type of the stage is q8_0 or q4_0. Such a stage also logs `receipts stay off for this stage` when it starts, and then no response carries a receipt | Set both KV cache types of the stage to f16 | +| `an audit covers CPU and CUDA alone` | The stage runs on Vulkan, Metal, ROCm or another backend without rounding profiles, or on two backends: `partial offload` or `op offload of large batches`. It logs `receipts stay off for this stage` when it starts, and no response carries a receipt | Serve on the CPU or CUDA. Offload every layer of the stage (`--n-gpu-layers -1`), or none with `--op-offload=false` | +| `which nothing commits` | A layer reads a value from another layer that is not the residual stream | Serve this model without receipts | +| `more than receipts leave unchecked` | Token-mixing ops read more than 1% of the weight bytes of the layer directly | Serve this model without receipts | +| `token mixing reaches the layer output without a weight matmul` | The classifier cannot bound a token-mixing region | Serve this model without receipts | +| `a token whose positions are not a text token's cannot be receipted` | The turn has image tokens | None. Such a turn gets no receipt | +| `a ubatch of embeddings cannot be receipted` | Stage 0 got embeddings and not tokens as its input | None | +| `a token shared by several sequences cannot be receipted` | One ubatch token belongs to more than one sequence | None | +| `the sequence's KV cells were loaded from saved state` | The stage restored a state. A hybrid stage does this for a cached prefix | None. The next turn that starts at position 0 gets a receipt | +| `the sequence's positions were shifted` | A context shift moved the positions of the sequence | None | +| `the KV cache was compacted` | A compaction moved the cells | None | +| `the sequence took KV cells from another sequence mid-turn` | A copy between sequences occurred after the turn started | None | +| `the turn's cached prefix is unknown` | The stage does not know what a cell of the prefix holds, or cannot replay the ubatch that wrote it. The text after it gives the cause | None. The next turn that starts at position 0 gets a receipt. See [The cached prefix](#the-cached-prefix) | +| `the ubatch that wrote position N of the cached prefix is no longer held` | A stage after the first dropped the input rows of that ubatch, past 1 GiB | None | +| `a stage with recurrent state cannot open the cached prefix of a turn` | A hybrid stage continued a sequence that it kept | None | +| `the recurrent state the turn started from is unknown` | A hybrid stage could not read the state | Read the stage log for the native error | +| `the turn recorded nothing` | No ubatch of the turn was recorded. The text after it gives the cause | Use the cause in the text | +| `the stage keeps ... bytes of receipts clients are challenging or may challenge at once` | The receipts of turns from the last 12 seconds, and of challenged turns, fill the 64 MiB | Send fewer bound requests at one time | +| `bytes of turns a client is challenging or may challenge at once` | The turns from the last 12 seconds, and the challenged turns, fill the 1 GiB of a stage | Send fewer requests at one time | +| `a ubatch the stage could not record ran during the turn` | A ubatch that the stage cannot record, for example of image embeddings, ran while the turn ran, and the turn continued a cached prefix | None. The next turn gets a receipt | +| `names a turn of another client that can still be challenged` | The request used the receipt id of another client's open turn | Use a new `x-receipt-id` or `x-request-id` for each request | +| `names a turn this client was signed a receipt for, which it can still challenge` | The request used the receipt id of an open turn of the same client key | Use a new `x-receipt-id` or `x-request-id` for each request | +| `the next stage did not answer`, `the next stage is not asked` | A later stage did not commit in 10 seconds, or it failed before and is not asked for a time | Make sure that the later stage runs. Wait 30 to 60 seconds | +| `this stage issues no receipts` | A later stage runs without `--receipts`. It is not asked again for 10 minutes | Start every stage with a receipts flag | + +Two errors stop a stage at startup: + +- `receipts need a plain KV cache`: the model has no attention KV cache. +- `receipts API on ... would expose opened activations to the network`: + the `--receipts-listen` address is not loopback. Use a loopback address, + or pass `--receipts-allow-remote`. + +### NO AUDIT causes + +| Report contains | Cause | What to do | +|---|---|---| +| `is neither a file here nor repo@revision/file on Hugging Face` | `--claimed-model` names no file and no Hugging Face file | Correct the path or the name | +| A connection error, or an HTTP status, before a receipt line | The command could not send the chat request, or Hugging Face is out of reach | Make sure that `--api` is correct and that the network works | +| `the node lists no model` | `GET /v1/models` on `--api` is empty | Wait until the model is loaded | +| `got no receipt:` | The turn got no receipt | See [A turn gets no receipt](#a-turn-gets-no-receipt) | +| `the receipt is version N, and this verifier checks version 7` | The node and the auditor are different releases | Use the same release on both sides | +| `the node ran ..., and this verifier runs ...` | The Skippy ABI or the llama.cpp build differs | Use the same release on both sides | +| `ran on backend ..., whose rounding no profile models` | A stage ran on Vulkan, Metal, ROCm or another backend without profiles | None. Such a stage cannot be audited. A current node issues no receipts on such a backend | +| `no rounding profile for ... weights` | A stage multiplies a weight type without a profile, for example q4_1 or q5_1 | None | +| `stored KV rows of type ...: an audit covers a cache of f16 or f32 rows` | A stage has a quantized KV cache | None. A current node issues no receipts with such a cache | +| `no reference decoding of ... output weights` | The auditor cannot decode the type of the output matrix | None | +| `this client cannot audit this model: ...; that is not a verdict on the node` | The claimed GGUF is over a limit of the auditor, or it is not a GGUF that the runtime loads | None | +| `names ..., not repo@commit/file on Hugging Face` | `recheck-receipt` has no `--claimed-model`, and the receipt does not name a pinned Hugging Face file | Pass `--claimed-model` | +| `not evidence of an audit:` | The file is not evidence. A signature or a VRF proof is wrong | Get the evidence file again | +| A `could not check:` line before `NO AUDIT` | One check could not run on this machine. The line gives the check and the cause | Use the cause in the line | + +`recheck-receipt` without `--claimed-model` and the Mesh auditor take the +model from the receipt. A receipt that names its model with a branch, a +tag or a short hash then gives no audit. + +### NO ANSWER causes + +The report names the request without an answer (`/receipts/open` or +`/receipts/rows`) and the cause. + +| Cause | What to do | +|---|---| +| A transport error, for example `Connection refused` | Make sure that `--receipts` names the receipts API of stage 0 | +| An error status against standalone `skippy serve`, from a command without `--receipts` | Pass `--receipts`. Only a Mesh node serves `/v1/receipts/open` | +| `404` with `no receipt` | The stage removed the record, or the id is unknown. Audit a new turn | +| `403` | The receipt is unbound. Send the request with `x-receipt-client-key` | +| `409` or `410` with `cannot_open` | The stage can no longer open the turn. The cache was full, a state load changed the cells, or the window ended. Audit a new turn | +| `503` | The stage was unloaded, or it was busy with other openings. A busy stage sends `Retry-After`, and the challenge can be sent again | +| `400` with `already read rows` | The stage read rows for 4 different rows requests of the receipt | Send the rows request that the opening draws | +| `400` with `was already challenged` | A bound receipt opens for one challenge | +| `the node did not sign its opening`, or a signature that is not correct | The answer cannot be held against the node. Read the stage log | +| A body that does not decode | The node sent no opening | + +## Files and their sensitivity + +| File | Location | Content | Sensitivity | +|---|---|---|---| +| Evidence file | The path that you give to `--evidence`. On a Mesh node, `receipt-evidence/