From f61b7eea39731462ed9ea0f3a924a37d0db9156d Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 24 Nov 2026 22:50:56 +0000 Subject: [PATCH 01/10] feat(modelpack): llm packs for llama.cpp, streamed hashing and extraction - modelpack + TS oracle accept task "llm" and engine "llama.cpp"; new valid-llm conformance case (engine version 0.6.0 in context.json). - modelpack hashes weights from a stream in 1 MiB chunks (verify_model_pack_reader, sha256_hex_file). - modelpack-sign: --task llm; zips straight to weights.bin, streaming each file in (.gguf Stored, the rest Deflated, zip64 when >= 4 GiB); hashes and self-verifies by streaming; knows llama.cpp 0.6.0. - app: verify and extract packs as streams; speech resolution skips llm packs; resolve_verified_llm(_in) returns the GGUF of the newest verified llm pack and fails closed (not called by the app yet). - llm-tiny fixture pack signed with the test key. --- app/src-tauri/src/models.rs | 263 +++++++++++++++--- core/src/modelpack.ts | 4 +- fixtures/modelpack/README.md | 1 + .../modelpack/cases/valid-llm/expected.json | 3 + .../modelpack/cases/valid-llm/manifest.json | 11 + .../modelpack/cases/valid-llm/weights.bin | Bin 0 -> 256 bytes fixtures/modelpack/context.json | 3 +- fixtures/modelpack/packs/README.md | 19 ++ .../modelpack/packs/llm-tiny/manifest.json | 11 + fixtures/modelpack/packs/llm-tiny/weights.bin | Bin 0 -> 147 bytes modelpack/src/lib.rs | 66 ++++- scripts/gen-modelpack-fixtures.ts | 17 ++ tools/modelpack-sign/Cargo.lock | 1 - tools/modelpack-sign/Cargo.toml | 1 - tools/modelpack-sign/src/lib.rs | 167 ++++++----- tools/modelpack-sign/src/main.rs | 5 +- tools/modelpack-sign/tests/llm_pack.rs | 76 +++++ 17 files changed, 527 insertions(+), 121 deletions(-) create mode 100644 fixtures/modelpack/cases/valid-llm/expected.json create mode 100644 fixtures/modelpack/cases/valid-llm/manifest.json create mode 100644 fixtures/modelpack/cases/valid-llm/weights.bin create mode 100644 fixtures/modelpack/packs/llm-tiny/manifest.json create mode 100644 fixtures/modelpack/packs/llm-tiny/weights.bin create mode 100644 tools/modelpack-sign/tests/llm_pack.rs diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 236da22..81412e6 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -9,10 +9,9 @@ //! the `fixtures/modelpack/cases/*` layout, which double as test packs). use std::collections::BTreeMap; -use std::io::Read; use std::path::{Component, Path, PathBuf}; -use modelpack::{verify_model_pack, PublicKey}; +use modelpack::{compare_semver, verify_model_pack_reader, PublicKey}; use serde::Serialize; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -37,9 +36,15 @@ fn engine_versions() -> BTreeMap { let mut m = BTreeMap::new(); m.insert("whisper.cpp".to_string(), "1.7.0".to_string()); m.insert("sherpa-onnx".to_string(), "2.0.1".to_string()); + // llama.cpp v0.6.0 (commit d812350), as vendored by llama-cpp-sys-2 =0.1.161 + // (spike S5). No llama.cpp is linked into the app yet. + m.insert("llama.cpp".to_string(), "0.6.0".to_string()); m } +/// The manifest `task` of a language-model pack (a GGUF for llama.cpp). +const LLM_TASK: &str = "llm"; + /// The verified/rejected status of a single model pack, surfaced to the UI. #[derive(Debug, Clone, Serialize)] pub struct PackStatus { @@ -73,8 +78,10 @@ impl PackStatus { } /// Verify a single pack directory and map the outcome to a [`PackStatus`]. A -/// missing `weights.bin` reads as empty bytes (→ hash-mismatch reject). Never -/// panics on missing/garbage files; every failure is a human-readable `reason`. +/// missing `weights.bin` reads as empty bytes (→ hash-mismatch reject). The +/// weights are hashed as a stream, never read into memory whole (LLM packs are +/// several GB). Never panics on missing/garbage files; every failure is a +/// human-readable `reason`. pub fn verify_pack_dir( dir: &Path, pubkey: &PublicKey<'_>, @@ -98,9 +105,12 @@ pub fn verify_pack_dir( } }; - let weights = std::fs::read(dir.join("weights.bin")).unwrap_or_default(); + let outcome = match std::fs::File::open(dir.join("weights.bin")) { + Ok(weights) => verify_model_pack_reader(&manifest_value, weights, pubkey, engine_versions), + Err(_) => verify_model_pack_reader(&manifest_value, std::io::empty(), pubkey, engine_versions), + }; - match verify_model_pack(&manifest_value, &weights, pubkey, engine_versions) { + match outcome { Ok(verified) => PackStatus { dir: dir_name, id: verified.manifest.id, @@ -227,11 +237,13 @@ fn zip_entry_is_safe(name: &str) -> bool { p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) } -/// Extract every file entry of the zip `weights` into `dest`, creating parent -/// dirs and skipping entries whose path would escape `dest`. -fn extract_zip_into(weights: &[u8], dest: &Path) -> Result<(), String> { - let reader = std::io::Cursor::new(weights); - let mut archive = zip::ZipArchive::new(reader) +/// Extract every file entry of the zip at `weights` into `dest`, creating +/// parent dirs and skipping entries whose path would escape `dest`. Entries are +/// streamed to disk, so a multi-GB GGUF never sits in memory. +fn extract_zip_into(weights: &Path, dest: &Path) -> Result<(), String> { + let file = std::fs::File::open(weights) + .map_err(|e| format!("opening {}: {e}", weights.display()))?; + let mut archive = zip::ZipArchive::new(std::io::BufReader::new(file)) .map_err(|e| format!("weights.bin is not a valid zip: {e}"))?; for i in 0..archive.len() { let mut entry = archive @@ -258,21 +270,63 @@ fn extract_zip_into(weights: &[u8], dest: &Path) -> Result<(), String> { std::fs::create_dir_all(parent) .map_err(|e| format!("creating dir {}: {e}", parent.display()))?; } - let mut buf = Vec::with_capacity(entry.size() as usize); - entry - .read_to_end(&mut buf) - .map_err(|e| format!("reading zip entry {rel_str}: {e}"))?; - std::fs::write(&out_path, &buf) + let mut out = std::fs::File::create(&out_path) .map_err(|e| format!("writing {}: {e}", out_path.display()))?; + std::io::copy(&mut entry, &mut out) + .map_err(|e| format!("extracting zip entry {rel_str}: {e}"))?; } Ok(()) } +/// True iff `path` is a readable zip archive. +fn is_zip_file(path: &Path) -> bool { + std::fs::File::open(path) + .map(|f| zip::ZipArchive::new(std::io::BufReader::new(f)).is_ok()) + .unwrap_or(false) +} + +/// The `sha256` string of the (already verified) manifest in `dir`. +fn manifest_sha256(dir: &Path) -> Result { + let bytes = std::fs::read(dir.join("manifest.json")) + .map_err(|e| format!("reading {}: {e}", dir.join("manifest.json").display()))?; + let value: Value = serde_json::from_slice(&bytes) + .map_err(|e| format!("parsing {}: {e}", dir.join("manifest.json").display()))?; + value + .get("sha256") + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| format!("manifest in {} has no sha256", dir.display())) +} + +/// Verify every pack directory in `packs_dir`, returning the verified ones. +fn verified_packs( + packs_dir: &Path, + pubkey: &PublicKey<'_>, + engine_versions: &BTreeMap, +) -> Vec<(PathBuf, PackStatus)> { + let mut out: Vec<(PathBuf, PackStatus)> = match std::fs::read_dir(packs_dir) { + Ok(entries) => entries + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_dir()) + .map(|p| { + let status = verify_pack_dir(&p, pubkey, engine_versions); + (p, status) + }) + .filter(|(_, status)| status.verified) + .collect(), + Err(_) => Vec::new(), + }; + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + /// Verified-pack resolver. Enumerates `packs_dir`, VERIFIES every -/// pack, extracts ONLY verified packs' `weights.bin` zips into a content- +/// pack, extracts ONLY verified speech packs' `weights.bin` zips into a content- /// addressed cache under `cache_base`, and returns the cache dir IFF it provides /// every model file the engine requires for `(asr_model, diarize)`. Fails closed /// at every step: no verified pack, or any missing required file, is an `Err`. +/// Language-model packs (`task: "llm"`) are left out; see [`resolve_verified_llm_in`]. /// /// The cache dir is keyed by the SHA-256 of the verified packs' `sha256` manifest /// strings (sorted ascending, `\n`-joined), so the same verified set always maps @@ -285,16 +339,11 @@ pub fn resolve_verified_models_dir_in( asr_model: engine::AsrModel, diarize: bool, ) -> Result { - let mut verified_dirs: Vec = match std::fs::read_dir(packs_dir) { - Ok(entries) => entries - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_dir()) - .filter(|p| verify_pack_dir(p, pubkey, engine_versions).verified) - .collect(), - Err(_) => Vec::new(), - }; - verified_dirs.sort(); + let verified_dirs: Vec = verified_packs(packs_dir, pubkey, engine_versions) + .into_iter() + .filter(|(_, status)| status.task != LLM_TASK) + .map(|(dir, _)| dir) + .collect(); if verified_dirs.is_empty() { return Err(format!( "no verified model pack found in {}", @@ -304,16 +353,7 @@ pub fn resolve_verified_models_dir_in( let mut sha_list: Vec = Vec::new(); for dir in &verified_dirs { - let bytes = std::fs::read(dir.join("manifest.json")) - .map_err(|e| format!("reading {}: {e}", dir.join("manifest.json").display()))?; - let value: Value = serde_json::from_slice(&bytes) - .map_err(|e| format!("parsing {}: {e}", dir.join("manifest.json").display()))?; - let sha = value - .get("sha256") - .and_then(Value::as_str) - .ok_or_else(|| format!("manifest in {} has no sha256", dir.display()))? - .to_string(); - sha_list.push(sha); + sha_list.push(manifest_sha256(dir)?); } sha_list.sort(); let combined_key = sha256_hex(sha_list.join("\n").as_bytes()); @@ -330,9 +370,9 @@ pub fn resolve_verified_models_dir_in( std::fs::create_dir_all(&composed) .map_err(|e| format!("creating cache dir {}: {e}", composed.display()))?; for dir in &verified_dirs { - let weights = std::fs::read(dir.join("weights.bin")).unwrap_or_default(); + let weights = dir.join("weights.bin"); // A non-zip weights.bin contributes no files — skip rather than abort. - if zip::ZipArchive::new(std::io::Cursor::new(&weights)).is_err() { + if !is_zip_file(&weights) { continue; } extract_zip_into(&weights, &composed)?; @@ -370,6 +410,84 @@ pub fn resolve_verified_models_dir( resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model, diarize) } +/// Verified LLM-pack resolver. Enumerates `packs_dir`, VERIFIES every pack, and +/// takes the verified `task: "llm"` pack with the highest version (ties: last +/// directory name). Its `weights.bin` zip is streamed into +/// `cache_base/verified-models/llm-/` (skipped when the `.complete` +/// marker is there) and the path of the single `.gguf` file inside is returned. +/// Fails closed: no verified LLM pack, a pack that is not a zip, or a pack +/// without exactly one top-level `.gguf` is an `Err`. Speech packs are never +/// returned, whatever files they hold. +#[allow(dead_code)] // Spike S5: not called by the app yet; P2 (local notes) will use it. +pub fn resolve_verified_llm_in( + packs_dir: &Path, + cache_base: &Path, + pubkey: &PublicKey<'_>, + engine_versions: &BTreeMap, +) -> Result { + let mut llm_packs: Vec<(PathBuf, PackStatus)> = + verified_packs(packs_dir, pubkey, engine_versions) + .into_iter() + .filter(|(_, status)| status.task == LLM_TASK) + .collect(); + llm_packs.sort_by(|a, b| compare_semver(&a.1.version, &b.1.version).then(a.0.cmp(&b.0))); + let Some((dir, status)) = llm_packs.pop() else { + return Err(format!( + "no verified LLM model pack found in {}", + packs_dir.display() + )); + }; + + let dest = cache_base + .join("verified-models") + .join(format!("llm-{}", manifest_sha256(&dir)?)); + let complete_marker = dest.join(".complete"); + if !complete_marker.exists() { + if dest.exists() { + std::fs::remove_dir_all(&dest) + .map_err(|e| format!("clearing partial cache {}: {e}", dest.display()))?; + } + std::fs::create_dir_all(&dest) + .map_err(|e| format!("creating cache dir {}: {e}", dest.display()))?; + extract_zip_into(&dir.join("weights.bin"), &dest)?; + std::fs::write(&complete_marker, b"") + .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display()))?; + } + + let ggufs: Vec = std::fs::read_dir(&dest) + .map_err(|e| format!("reading cache dir {}: {e}", dest.display()))? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| { + p.is_file() + && p.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("gguf")) + }) + .collect(); + match ggufs.as_slice() { + [gguf] => Ok(gguf.clone()), + [] => Err(format!("verified LLM pack {} holds no .gguf file", status.id)), + _ => Err(format!( + "verified LLM pack {} holds more than one .gguf file", + status.id + )), + } +} + +/// AppHandle wrapper around [`resolve_verified_llm_in`]. +#[allow(dead_code)] // Spike S5: not called by the app yet; P2 (local notes) will use it. +pub fn resolve_verified_llm(app: &tauri::AppHandle) -> Result { + let packs = packs_dir(app)?; + let cache_base = app + .path() + .app_data_dir() + .map_err(|e| format!("cannot resolve app data dir: {e}"))?; + let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); + let versions = engine_versions(); + resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) +} + #[cfg(test)] mod tests { use super::*; @@ -600,4 +718,71 @@ mod tests { let _ = fs::remove_dir_all(&cache_base); } + + /// Copy the committed fixture pack `name` into `packs//`. + fn copy_fixture_pack(name: &str, packs: &Path) -> PathBuf { + let src = repo_root().join("fixtures/modelpack/packs").join(name); + let dest = packs.join(name); + fs::create_dir_all(&dest).unwrap(); + for file in ["manifest.json", "weights.bin"] { + fs::copy(src.join(file), dest.join(file)).unwrap(); + } + dest + } + + /// A signed `task: "llm"` pack resolves to the GGUF inside it, even with a + /// speech pack alongside. + #[test] + fn resolve_verified_llm_in_returns_the_gguf_of_a_signed_llm_pack() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = repo_root().join("fixtures/modelpack/packs"); + let cache_base = unique_tmp("llm-ok"); + + let gguf = resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) + .expect("the committed llm fixture pack must resolve"); + + assert_eq!(gguf.file_name().unwrap(), "tiny.gguf"); + assert_eq!(fs::read(&gguf).unwrap(), b"GGUF fixture: not a real model\n"); + + let _ = fs::remove_dir_all(&cache_base); + } + + /// A pack whose weights.bin was changed after signing is never resolved. + #[test] + fn resolve_verified_llm_in_rejects_tampered_weights() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = unique_tmp("llm-tampered-packs"); + let pack = copy_fixture_pack("llm-tiny", &packs); + let mut weights = fs::read(pack.join("weights.bin")).unwrap(); + let last = weights.len() - 1; + weights[last] ^= 0x01; + fs::write(pack.join("weights.bin"), &weights).unwrap(); + let cache_base = unique_tmp("llm-tampered-cache"); + + let err = resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) + .expect_err("a tampered llm pack must not be trusted"); + + assert!(err.contains("no verified LLM model pack found"), "got: {err}"); + let _ = fs::remove_dir_all(&packs); + let _ = fs::remove_dir_all(&cache_base); + } + + /// A verified speech pack is never handed out as a language model. + #[test] + fn resolve_verified_llm_in_never_returns_an_asr_pack() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = unique_tmp("llm-asr-only-packs"); + copy_fixture_pack("asr-small-en", &packs); + let cache_base = unique_tmp("llm-asr-only-cache"); + + let err = resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) + .expect_err("an asr pack is not an llm pack"); + + assert!(err.contains("no verified LLM model pack found"), "got: {err}"); + let _ = fs::remove_dir_all(&packs); + let _ = fs::remove_dir_all(&cache_base); + } } diff --git a/core/src/modelpack.ts b/core/src/modelpack.ts index bb4d3ed..18ccc8a 100644 --- a/core/src/modelpack.ts +++ b/core/src/modelpack.ts @@ -31,11 +31,11 @@ import { createHash, verify as nodeVerify, createPublicKey } from "node:crypto"; import type { KeyObject } from "node:crypto"; /** Engines this build knows how to drive. */ -export const ENGINES = ["whisper.cpp", "sherpa-onnx"] as const; +export const ENGINES = ["whisper.cpp", "sherpa-onnx", "llama.cpp"] as const; export type Engine = (typeof ENGINES)[number]; /** Tasks a model pack can perform. */ -export const TASKS = ["asr", "diarization"] as const; +export const TASKS = ["asr", "diarization", "llm"] as const; export type Task = (typeof TASKS)[number]; /** diff --git a/fixtures/modelpack/README.md b/fixtures/modelpack/README.md index 76fbba5..13b3e93 100644 --- a/fixtures/modelpack/README.md +++ b/fixtures/modelpack/README.md @@ -52,6 +52,7 @@ are fixed in the script). It rewrites `cases/` and `context.json` only. | case | outcome | proves | | --- | --- | --- | | `valid` | ok | canonicalization + ed25519 parity (the decisive cross-impl check) | +| `valid-llm` | ok | `task: "llm"` on the `llama.cpp` engine is accepted | | `tampered-weights` | reject | sha256 mismatch detected | | `unsigned` | reject | empty signature fails closed | | `untrusted` | reject | signature by a different key rejected | diff --git a/fixtures/modelpack/cases/valid-llm/expected.json b/fixtures/modelpack/cases/valid-llm/expected.json new file mode 100644 index 0000000..e1ff86d --- /dev/null +++ b/fixtures/modelpack/cases/valid-llm/expected.json @@ -0,0 +1,3 @@ +{ + "outcome": "ok" +} diff --git a/fixtures/modelpack/cases/valid-llm/manifest.json b/fixtures/modelpack/cases/valid-llm/manifest.json new file mode 100644 index 0000000..2cea874 --- /dev/null +++ b/fixtures/modelpack/cases/valid-llm/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "acme/qwen3-4b-instruct", + "version": "1.2.3", + "engine": "llama.cpp", + "engine_min_version": "0.6.0", + "task": "llm", + "license": "Apache-2.0", + "attribution": "Acme Language Labs", + "sha256": "c8c6e02d597fa6c407a5fec30c981c7bbad08972240eea89841b8f37e2fbf32c", + "signature": "X4BLQdG+1TRWoNXBdBWatNKWzbzsbrylnohCmys5TNVhHvP+XPfluLrg49KFRtZz2CRfYep+Tn8iEpKmBoYUBA==" +} diff --git a/fixtures/modelpack/cases/valid-llm/weights.bin b/fixtures/modelpack/cases/valid-llm/weights.bin new file mode 100644 index 0000000000000000000000000000000000000000..b7c580c862c0f34da17ee679f9f357c999a432ca GIT binary patch literal 256 zcmV+b0ssC7CPid}qQT(*9z9%pnz`8b7By6JlCjY54lPV;imAxw1|>vef}z0Q{vAA9 zdYQP__7yZ!a*?pl?hPzUYKf@F<^?1}Vu7H)-u)aqT6vha*7X!KQgM*4&g~2Io=EW`(4~;sGE( zUVWUq+W8naR&|uK((w>4PHl{<%IOFvMrDMf!r=fPK3#m9y4m;_HdS$g2v44R8 literal 0 HcmV?d00001 diff --git a/fixtures/modelpack/context.json b/fixtures/modelpack/context.json index 93c5e8a..a04e5d7 100644 --- a/fixtures/modelpack/context.json +++ b/fixtures/modelpack/context.json @@ -3,6 +3,7 @@ "pubkeyRawHex": "d47b104c2709d9e5266b996692355dcc271ed29dc46b1cb0a65378c7265c4a95", "engineVersions": { "whisper.cpp": "1.7.0", - "sherpa-onnx": "1.13.2" + "sherpa-onnx": "1.13.2", + "llama.cpp": "0.6.0" } } diff --git a/fixtures/modelpack/packs/README.md b/fixtures/modelpack/packs/README.md index cb3de89..dee46ea 100644 --- a/fixtures/modelpack/packs/README.md +++ b/fixtures/modelpack/packs/README.md @@ -17,6 +17,11 @@ exist only to satisfy the resolver's required-file existence check `small.en` (`sherpa-onnx-whisper-small.en/small.en-{encoder,decoder}.int8.onnx`, `…-tokens.txt`, `silero_vad.onnx`) — all empty. +- `llm-tiny/` — `id = test/llm-tiny`, `engine = llama.cpp`, `task = llm`. Its + `weights.bin` zips (Stored, uncompressed) one file, `tiny.gguf`, holding the + text `GGUF fixture: not a real model` and a newline. Used by the + `resolve_verified_llm_in` tests; the speech resolver must ignore it. + ## Regenerating ```sh @@ -34,3 +39,17 @@ cargo run --manifest-path tools/modelpack-sign/Cargo.toml -- pack \ --attribution "Sightline Test ASR small.en" rm -rf "$TMP" ``` + +For `llm-tiny/`: + +```sh +TMP=$(mktemp -d) +printf 'GGUF fixture: not a real model\n' > "$TMP/tiny.gguf" +cargo run --manifest-path tools/modelpack-sign/Cargo.toml -- pack \ + --model-dir "$TMP" --out fixtures/modelpack/packs/llm-tiny \ + --key fixtures/modelpack/keys/test-private.pkcs8.pem \ + --id test/llm-tiny --version 1.0.0 --engine llama.cpp \ + --engine-min-version 0.6.0 --task llm --license Apache-2.0 \ + --attribution "Test LLM pack (not a real model)" +rm -rf "$TMP" +``` diff --git a/fixtures/modelpack/packs/llm-tiny/manifest.json b/fixtures/modelpack/packs/llm-tiny/manifest.json new file mode 100644 index 0000000..0d8b869 --- /dev/null +++ b/fixtures/modelpack/packs/llm-tiny/manifest.json @@ -0,0 +1,11 @@ +{ + "attribution": "Test LLM pack (not a real model)", + "engine": "llama.cpp", + "engine_min_version": "0.6.0", + "id": "test/llm-tiny", + "license": "Apache-2.0", + "sha256": "2c7be4c8a013dd3a8ae48d661a66b871592788947e821867fbc2cdeaf8db2054", + "signature": "rxdzF4XMkJaLBD1PBrHXoajd99h0IItotAVnyA8Pxf2Dc2lslvP29uL2Wv4MlJB1LYmQRjmmXLsz5vVAc+lyAg==", + "task": "llm", + "version": "1.0.0" +} \ No newline at end of file diff --git a/fixtures/modelpack/packs/llm-tiny/weights.bin b/fixtures/modelpack/packs/llm-tiny/weights.bin new file mode 100644 index 0000000000000000000000000000000000000000..7d1db8b7121f3aa3486eec3d848411b40d00ad83 GIT binary patch literal 147 zcmWIWW@h1H00E2D6|sLZwO`2t*&xgb#3h+|m3ryvrD^W&p>7IknH43aMX6Q_dHE#@ yi3&xji8%_n`6;P6TmjyUOkB*k%>fz(21^=26x`GRZ&o&t03#5Z18Fx9hXDZn, engine_versions: &BTreeMap, +) -> Result { + verify_model_pack_reader(manifest_value, weights, pubkey, engine_versions) +} + +/// Bytes read per step when hashing weights. Packs can be several GB (a Q4 +/// 4B LLM is ~2.4 GB), so weights are never held in memory whole. +pub const HASH_CHUNK_BYTES: usize = 1 << 20; + +/// Lowercase-hex SHA-256 of everything `reader` yields, read +/// [`HASH_CHUNK_BYTES`] at a time. +pub fn sha256_hex_reader(mut reader: R) -> std::io::Result { + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; HASH_CHUNK_BYTES]; + loop { + let n = match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e), + }; + hasher.update(&buf[..n]); + } + Ok(hex_encode(&hasher.finalize())) +} + +/// Lowercase-hex SHA-256 of the file at `path`, streamed in chunks. +pub fn sha256_hex_file(path: &Path) -> std::io::Result { + sha256_hex_reader(std::fs::File::open(path)?) +} + +/// [`verify_model_pack`] over a weights STREAM (e.g. an open `weights.bin`), +/// hashed in [`HASH_CHUNK_BYTES`] chunks so multi-GB packs never sit in RAM. +/// Same steps, same order, same reasons; a read error mid-stream fails closed. +pub fn verify_model_pack_reader( + manifest_value: &Value, + weights: R, + pubkey: &PublicKey<'_>, + engine_versions: &BTreeMap, ) -> Result { // 1. structural validation let manifest = validate_manifest(manifest_value)?; // 2. weights integrity - let actual = hex_encode(&Sha256::digest(weights)); + let actual = sha256_hex_reader(weights) + .map_err(|e| format!("cannot read weights (tampered or corrupt): {e}"))?; if !timing_safe_hex_equal(&actual, &manifest.sha256) { return Err("weights hash mismatch (tampered or corrupt)".to_string()); } @@ -375,6 +416,25 @@ mod tests { assert!(validate_manifest(&m).unwrap_err().contains("not valid semver")); } + /// A file longer than one hash chunk hashes to its SHA-256 (the literal was + /// computed independently with `shasum -a 256` over the same bytes). + #[test] + fn streamed_hash_of_a_file_larger_than_one_chunk() { + let len = (1usize << 20) + 4097; + let bytes: Vec = (0..len).map(|i| ((i * 31 + 7) & 0xff) as u8).collect(); + let path = std::env::temp_dir().join(format!("modelpack-chunk-{}.bin", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + + let digest = sha256_hex_file(&path).unwrap(); + let _ = std::fs::remove_file(&path); + + assert!(len > HASH_CHUNK_BYTES); + assert_eq!( + digest, + "b0fee64e0701324ea24d718618eb8e39ec084ac78a92948424f1b23b16e7804a" + ); + } + #[test] fn non_object_manifest_is_rejected() { assert_eq!( diff --git a/scripts/gen-modelpack-fixtures.ts b/scripts/gen-modelpack-fixtures.ts index a0ad9a4..17ba3e8 100644 --- a/scripts/gen-modelpack-fixtures.ts +++ b/scripts/gen-modelpack-fixtures.ts @@ -51,6 +51,7 @@ const untrustedPrivKey = createPrivateKey(untrustedPrivPem); const ENGINE_VERSIONS = { "whisper.cpp": "1.7.0", "sherpa-onnx": "1.13.2", + "llama.cpp": "0.6.0", }; // --- helpers --------------------------------------------------------------- @@ -129,6 +130,22 @@ function baseManifest(overrides: Record = {}): Record); + writeCase("valid-llm", { ...m, signature }, { outcome: "ok" }, weights); +} + // === reject: tampered-weights (flip a byte after signing) ================== { const weights = makeWeights(2); diff --git a/tools/modelpack-sign/Cargo.lock b/tools/modelpack-sign/Cargo.lock index 5d171fd..374526a 100644 --- a/tools/modelpack-sign/Cargo.lock +++ b/tools/modelpack-sign/Cargo.lock @@ -586,7 +586,6 @@ dependencies = [ "modelpack", "rand_core", "serde_json", - "sha2", "walkdir", "zip", ] diff --git a/tools/modelpack-sign/Cargo.toml b/tools/modelpack-sign/Cargo.toml index 0ae88a6..5349ba8 100644 --- a/tools/modelpack-sign/Cargo.toml +++ b/tools/modelpack-sign/Cargo.toml @@ -9,7 +9,6 @@ license = "Apache-2.0" modelpack = { path = "../../modelpack" } ed25519-dalek = { version = "2", features = ["rand_core", "pkcs8", "pem"] } rand_core = { version = "0.6", features = ["getrandom"] } -sha2 = "0.10" base64 = "0.22" serde_json = "1" anyhow = "1" diff --git a/tools/modelpack-sign/src/lib.rs b/tools/modelpack-sign/src/lib.rs index afa00a5..0c4ca47 100644 --- a/tools/modelpack-sign/src/lib.rs +++ b/tools/modelpack-sign/src/lib.rs @@ -7,7 +7,7 @@ //! and verifies. use std::collections::BTreeMap; -use std::io::{Cursor, Read, Write}; +use std::io::Write; use std::path::Path; use anyhow::{bail, Context, Result}; @@ -18,7 +18,6 @@ use ed25519_dalek::pkcs8::spki::EncodePublicKey; use ed25519_dalek::pkcs8::{DecodePrivateKey, EncodePrivateKey}; use ed25519_dalek::{Signer, SigningKey}; use modelpack::{Manifest, PublicKey}; -use sha2::{Digest, Sha256}; /// Engine versions this build's self-check pretends to bundle. Used only for the /// post-pack self-verification (the producer must prove the pack it just wrote @@ -27,6 +26,8 @@ pub fn self_check_engine_versions() -> BTreeMap { let mut m = BTreeMap::new(); m.insert("whisper.cpp".to_string(), "1.7.0".to_string()); m.insert("sherpa-onnx".to_string(), "1.13.2".to_string()); + // llama.cpp v0.6.0 (commit d812350), as vendored by llama-cpp-sys-2 =0.1.161. + m.insert("llama.cpp".to_string(), "0.6.0".to_string()); m } @@ -169,65 +170,82 @@ pub fn keygen(out_dir: &Path) -> Result<(std::path::PathBuf, std::path::PathBuf) Ok((private_path, public_path)) } -/// Recursively zip the CONTENTS of `model_dir` into an in-memory byte vector, -/// preserving relative paths (`model_dir/sub/x.onnx` -> entry `sub/x.onnx`). -pub fn zip_model_dir(model_dir: &Path) -> Result> { +/// True for files that are already compressed model weights (GGUF): they are +/// Stored, not Deflated, so packing a multi-GB LLM costs no CPU for no gain +/// and the entry's bytes sit uncompressed in the zip. +fn store_uncompressed(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("gguf")) +} + +/// Recursively zip the CONTENTS of `model_dir` into the file `out`, preserving +/// relative paths (`model_dir/sub/x.onnx` -> entry `sub/x.onnx`). Each file is +/// streamed into the zip, so memory use stays flat however large the weights +/// are. GGUF files are Stored; everything else is Deflated (as before). Files of +/// 4 GiB or more get zip64 headers. +pub fn zip_model_dir_to(model_dir: &Path, out: &Path) -> Result<()> { if !model_dir.is_dir() { bail!("model dir {} is not a directory", model_dir.display()); } - let mut cursor = Cursor::new(Vec::::new()); - { - let mut zip = zip::ZipWriter::new(&mut cursor); - let options: zip::write::FileOptions<()> = - zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated); - - // Collect + sort entries so the zip is deterministic regardless of FS order. - let mut entries: Vec<_> = walkdir::WalkDir::new(model_dir) - .sort_by_file_name() - .into_iter() - .collect::, _>>() - .context("walking model dir")?; - entries.sort_by(|a, b| a.path().cmp(b.path())); - - for entry in entries { - let path = entry.path(); - let rel = path - .strip_prefix(model_dir) - .context("stripping model-dir prefix")?; - if rel.as_os_str().is_empty() { - continue; // the root itself - } - let rel_str = rel - .to_str() - .with_context(|| format!("non-UTF-8 path: {}", rel.display()))? - .replace('\\', "/"); - if entry.file_type().is_dir() { - zip.add_directory(format!("{rel_str}/"), options) - .context("adding dir to zip")?; - } else if entry.file_type().is_file() { - zip.start_file(rel_str, options) - .context("starting zip file entry")?; - let mut f = std::fs::File::open(path) - .with_context(|| format!("opening {}", path.display()))?; - let mut buf = Vec::new(); - f.read_to_end(&mut buf) - .with_context(|| format!("reading {}", path.display()))?; - zip.write_all(&buf).context("writing zip file bytes")?; - } + let file = std::fs::File::create(out) + .with_context(|| format!("creating {}", out.display()))?; + let mut zip = zip::ZipWriter::new(std::io::BufWriter::new(file)); + + // Collect + sort entries so the zip is deterministic regardless of FS order. + let mut entries: Vec<_> = walkdir::WalkDir::new(model_dir) + .sort_by_file_name() + .into_iter() + .collect::, _>>() + .context("walking model dir")?; + entries.sort_by(|a, b| a.path().cmp(b.path())); + + for entry in entries { + let path = entry.path(); + let rel = path + .strip_prefix(model_dir) + .context("stripping model-dir prefix")?; + if rel.as_os_str().is_empty() { + continue; // the root itself + } + let rel_str = rel + .to_str() + .with_context(|| format!("non-UTF-8 path: {}", rel.display()))? + .replace('\\', "/"); + if entry.file_type().is_dir() { + let options: zip::write::FileOptions<()> = zip::write::FileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + zip.add_directory(format!("{rel_str}/"), options) + .context("adding dir to zip")?; + } else if entry.file_type().is_file() { + let size = entry + .metadata() + .with_context(|| format!("reading metadata of {}", path.display()))? + .len(); + let method = if store_uncompressed(path) { + zip::CompressionMethod::Stored + } else { + zip::CompressionMethod::Deflated + }; + let options: zip::write::FileOptions<()> = zip::write::FileOptions::default() + .compression_method(method) + .large_file(size >= u64::from(u32::MAX)); + zip.start_file(rel_str, options) + .context("starting zip file entry")?; + let mut f = std::fs::File::open(path) + .with_context(|| format!("opening {}", path.display()))?; + std::io::copy(&mut f, &mut zip) + .with_context(|| format!("streaming {} into the zip", path.display()))?; } - zip.finish().context("finishing zip")?; - } - Ok(cursor.into_inner()) -} - -/// Lowercase hex sha256 of the given bytes. -pub fn sha256_hex(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - let mut out = String::with_capacity(digest.len() * 2); - for b in digest { - out.push_str(&format!("{b:02x}")); } - out + let mut writer = zip.finish().context("finishing zip")?; + writer.flush().context("flushing zip")?; + writer + .into_inner() + .map_err(|e| anyhow::anyhow!("flushing zip: {}", e.error()))? + .sync_all() + .context("syncing zip")?; + Ok(()) } /// Metadata for a pack, mirroring the eight signed manifest fields (minus the @@ -278,8 +296,10 @@ pub fn build_manifest_json(meta: &PackMeta, sha256: &str, signature: &str) -> se }) } -/// Full `pack` pipeline: zip the model dir, hash, sign, write the pack, then -/// self-verify with the real `modelpack::verify_model_pack` before returning. +/// Full `pack` pipeline: zip the model dir straight into `weights.bin`, hash it +/// in chunks, sign, write the manifest, then self-verify (again streaming) with +/// the real `modelpack` verifier before returning. Nothing is held in memory +/// whole, so multi-GB LLM packs sign in flat memory. pub fn pack( model_dir: &Path, out_dir: &Path, @@ -289,17 +309,16 @@ pub fn pack( let signing = SigningKey::from_pkcs8_pem(private_pem).context("loading signing key from PKCS8 PEM")?; - let zip_bytes = zip_model_dir(model_dir)?; - let sha256 = sha256_hex(&zip_bytes); - let signature = sign_manifest(&signing, meta, &sha256); - let manifest_json = build_manifest_json(meta, &sha256, &signature); - std::fs::create_dir_all(out_dir) .with_context(|| format!("creating pack out-dir {}", out_dir.display()))?; let weights_path = out_dir.join("weights.bin"); let manifest_path = out_dir.join("manifest.json"); - std::fs::write(&weights_path, &zip_bytes) - .with_context(|| format!("writing {}", weights_path.display()))?; + zip_model_dir_to(model_dir, &weights_path)?; + let sha256 = modelpack::sha256_hex_file(&weights_path) + .with_context(|| format!("hashing {}", weights_path.display()))?; + let signature = sign_manifest(&signing, meta, &sha256); + let manifest_json = build_manifest_json(meta, &sha256, &signature); + let manifest_pretty = serde_json::to_string_pretty(&manifest_json).context("serializing manifest json")?; std::fs::write(&manifest_path, manifest_pretty.as_bytes()) @@ -312,9 +331,11 @@ pub fn pack( .to_public_key_pem(LineEnding::LF) .context("deriving public SPKI PEM for self-check")?; let engine_versions = self_check_engine_versions(); - modelpack::verify_model_pack( + let weights = std::fs::File::open(&weights_path) + .with_context(|| format!("opening {}", weights_path.display()))?; + modelpack::verify_model_pack_reader( &manifest_json, - &zip_bytes, + weights, &PublicKey::SpkiPem(&public_pem), &engine_versions, ) @@ -323,21 +344,21 @@ pub fn pack( Ok(()) } -/// Verify an existing pack directory against an SPKI public PEM. Returns the -/// attribution on success. +/// Verify an existing pack directory against an SPKI public PEM, streaming +/// `weights.bin`. Returns the attribution on success. pub fn verify_pack(pack_dir: &Path, public_pem: &str) -> Result { let manifest_path = pack_dir.join("manifest.json"); let weights_path = pack_dir.join("weights.bin"); let manifest_bytes = std::fs::read(&manifest_path) .with_context(|| format!("reading {}", manifest_path.display()))?; - let weights = std::fs::read(&weights_path) - .with_context(|| format!("reading {}", weights_path.display()))?; + let weights = std::fs::File::open(&weights_path) + .with_context(|| format!("opening {}", weights_path.display()))?; let value: serde_json::Value = serde_json::from_slice(&manifest_bytes).context("parsing manifest.json")?; let engine_versions = self_check_engine_versions(); - let verified = modelpack::verify_model_pack( + let verified = modelpack::verify_model_pack_reader( &value, - &weights, + weights, &PublicKey::SpkiPem(public_pem), &engine_versions, ) diff --git a/tools/modelpack-sign/src/main.rs b/tools/modelpack-sign/src/main.rs index 075f07b..5d73948 100644 --- a/tools/modelpack-sign/src/main.rs +++ b/tools/modelpack-sign/src/main.rs @@ -65,6 +65,8 @@ enum Command { enum Task { Asr, Diarization, + /// A local language model (a GGUF for the `llama.cpp` engine). + Llm, } impl Task { @@ -72,6 +74,7 @@ impl Task { match self { Task::Asr => "asr", Task::Diarization => "diarization", + Task::Llm => "llm", } } } @@ -117,7 +120,7 @@ fn main() -> Result<()> { }; pack(&model_dir, &out, &private_pem, &meta)?; println!("OK: wrote signed pack to {}", out.display()); - println!(" (self-verified with modelpack::verify_model_pack)"); + println!(" (self-verified with the modelpack verifier)"); } Command::Verify { pack, pubkey } => { let public_pem = std::fs::read_to_string(&pubkey)?; diff --git a/tools/modelpack-sign/tests/llm_pack.rs b/tools/modelpack-sign/tests/llm_pack.rs new file mode 100644 index 0000000..91b3a0f --- /dev/null +++ b/tools/modelpack-sign/tests/llm_pack.rs @@ -0,0 +1,76 @@ +//! `modelpack-sign pack --task llm` produces a pack the real verifier (the +//! `modelpack` crate the app uses) accepts. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::process::Command; + +use modelpack::{verify_model_pack_reader, PublicKey}; + +fn signer() -> Command { + Command::new(env!("CARGO_BIN_EXE_modelpack-sign")) +} + +fn unique_tmp(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "mps-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} + +#[test] +fn task_llm_pack_is_accepted_by_the_real_verifier() { + let tmp = unique_tmp("llm"); + let keys = tmp.join("keys"); + let model = tmp.join("model"); + let out = tmp.join("pack"); + std::fs::create_dir_all(&model).unwrap(); + std::fs::write(model.join("tiny.gguf"), b"GGUF tiny test weights").unwrap(); + + let keygen = signer() + .args(["keygen", "--out-dir"]) + .arg(&keys) + .output() + .unwrap(); + assert!(keygen.status.success(), "keygen: {}", String::from_utf8_lossy(&keygen.stderr)); + + let pack = signer() + .arg("pack") + .arg("--model-dir") + .arg(&model) + .arg("--out") + .arg(&out) + .arg("--key") + .arg(keys.join("private.pkcs8.pem")) + .args(["--id", "test/qwen3-4b-instruct-2507"]) + .args(["--version", "1.0.0"]) + .args(["--engine", "llama.cpp"]) + .args(["--engine-min-version", "0.6.0"]) + .args(["--task", "llm"]) + .args(["--license", "Apache-2.0"]) + .args(["--attribution", "Qwen Team (test)"]) + .output() + .unwrap(); + assert!(pack.status.success(), "pack: {}", String::from_utf8_lossy(&pack.stderr)); + + let manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(out.join("manifest.json")).unwrap()).unwrap(); + let public_pem = std::fs::read_to_string(keys.join("public.spki.pem")).unwrap(); + let weights = std::fs::File::open(out.join("weights.bin")).unwrap(); + let mut engines = BTreeMap::new(); + engines.insert("llama.cpp".to_string(), "0.6.0".to_string()); + + let verified = + verify_model_pack_reader(&manifest, weights, &PublicKey::SpkiPem(&public_pem), &engines) + .expect("the signed llm pack must verify"); + + assert_eq!(verified.manifest.task, "llm"); + assert_eq!(verified.manifest.engine, "llama.cpp"); + assert_eq!(verified.attribution, "Qwen Team (test)"); + + let _ = std::fs::remove_dir_all(&tmp); +} From fcde173568364793cbda08d075921c2c9a28cfbb Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 24 Nov 2026 22:50:56 +0000 Subject: [PATCH 02/10] spike(s5): link llama.cpp and sherpa-onnx in one CPU-only binary spikes/s5-llama pins llama-cpp-2 =0.1.161 (llama.cpp v0.6.0) next to the engine. --self-check starts onnxruntime and the llama.cpp CPU backend in one process; --model loads a GGUF and reports load time, tokens/s and peak RSS. .cargo/config.toml keeps Metal and OpenSSL out of the CMake build and builds llama.cpp with the static CRT to match sherpa-onnx on Windows. The zero-egress gate also scans the spike (all targets), and a new CI job builds and self-checks it on Linux, macOS and Windows, the Linux build in a network namespace with no network. --- .github/workflows/ci.yml | 66 + scripts/check-no-network.sh | 9 +- spikes/s5-llama/.cargo/config.toml | 20 + spikes/s5-llama/.gitignore | 1 + spikes/s5-llama/Cargo.lock | 1919 ++++++++++++++++++++++++++++ spikes/s5-llama/Cargo.toml | 41 + spikes/s5-llama/src/main.rs | 310 +++++ 7 files changed, 2365 insertions(+), 1 deletion(-) create mode 100644 spikes/s5-llama/.cargo/config.toml create mode 100644 spikes/s5-llama/.gitignore create mode 100644 spikes/s5-llama/Cargo.lock create mode 100644 spikes/s5-llama/Cargo.toml create mode 100644 spikes/s5-llama/src/main.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df10e34..ac216f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,8 @@ # modelpack-sign— producer signer conformance (Rust signer == TS signature). # asr-bench — eval bench: leaderboard-scorer parity, segmenter, bootstrap. # windows — MSVC static-link of sherpa-onnx + engine/app tests on Windows. +# s5-llama — spike S5: llama.cpp + sherpa-onnx linked into one binary on +# Linux/macOS/Windows; the Linux build runs with no network. # # The same gate is provable locally any time via scripts/check-no-network.sh. name: ci @@ -166,3 +168,67 @@ jobs: run: npm ci && npm run build - name: Test app backend (engine + sherpa-onnx linked into Tauri) run: cargo test --manifest-path app/src-tauri/Cargo.toml + + # Spike S5 (docs/spikes/s5-llm-packaging.md): llama.cpp (llama-cpp-2) and + # sherpa-onnx (via engine) statically linked into ONE CPU-only binary. The + # self-check starts onnxruntime and the llama.cpp CPU backend in one process, + # so duplicate symbols, CRT or threading clashes fail here. No model needed. + s5-llama: + name: spike S5 llama.cpp + sherpa-onnx link (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + # .cargo/config.toml there keeps the build CPU-only (no Metal, no OpenSSL). + working-directory: spikes/s5-llama + env: + SHERPA_ARCHIVE: sherpa-onnx-v2.0.1-linux-x64-static-lib.tar.bz2 + SHERPA_ARCHIVE_SHA256: 55cfadf65ba50d0afc1a802b7a337942819e51c94a5b5a384def1978f7c70871 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + # Linux builds from scratch on purpose: a cached llama.cpp build would + # skip the CMake step the no-network build below is there to prove. + - uses: Swatinem/rust-cache@v2 + if: runner.os != 'Linux' + with: + workspaces: spikes/s5-llama + # Linux: everything the build needs is fetched first (crates, plus the + # sherpa-onnx static libs checked against a pinned SHA-256)... + - name: Fetch crates and the pinned sherpa-onnx archive (Linux) + if: runner.os == 'Linux' + run: | + mkdir -p "$RUNNER_TEMP/sherpa" + curl -sSfL -o "$RUNNER_TEMP/sherpa/$SHERPA_ARCHIVE" \ + "https://github.com/k2-fsa/sherpa-onnx/releases/download/v2.0.1/$SHERPA_ARCHIVE" + echo "$SHERPA_ARCHIVE_SHA256 $RUNNER_TEMP/sherpa/$SHERPA_ARCHIVE" | sha256sum -c - + cargo fetch --locked + # ...then the build runs in a new network namespace with no interfaces + # but loopback, so any build-script or CMake download fails the job. + - name: Build with no network (Linux) + if: runner.os == 'Linux' + run: | + # Ubuntu 24.04 restricts unprivileged user namespaces by default. + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true + unshare --user --map-root-user --net -- env \ + SHERPA_ONNX_ARCHIVE_DIR="$RUNNER_TEMP/sherpa" bash -c ' + if curl -sS -m 5 -o /dev/null https://github.com; then + echo "network is reachable inside the namespace; the check would prove nothing" >&2 + exit 1 + fi + cargo build --offline --locked --release' + - name: Build (macOS, Windows) + if: runner.os != 'Linux' + run: cargo build --locked --release + - name: Self-check (sherpa-onnx + llama.cpp backend in one process) + run: ./target/release/s5-llama --self-check + - name: Baseline build without llama.cpp, for the size comparison + run: | + cargo build --locked --release --no-default-features --target-dir target-nollama + ./target-nollama/release/s5-llama --self-check + - name: Binary sizes (with / without llama.cpp) + run: ls -l target/release/s5-llama target/release/s5-llama.exe target-nollama/release/s5-llama target-nollama/release/s5-llama.exe 2>/dev/null || true diff --git a/scripts/check-no-network.sh b/scripts/check-no-network.sh index 635329b..673f76c 100755 --- a/scripts/check-no-network.sh +++ b/scripts/check-no-network.sh @@ -21,6 +21,7 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" APP_MANIFEST="$REPO_ROOT/app/src-tauri/Cargo.toml" ENGINE_MANIFEST="$REPO_ROOT/engine/Cargo.toml" MODELPACK_MANIFEST="$REPO_ROOT/modelpack/Cargo.toml" +SPIKE_LLAMA_MANIFEST="$REPO_ROOT/spikes/s5-llama/Cargo.toml" # Denylist: HTTP/WebSocket clients, TLS stacks, and Tauri plugins that open # network connections or external URLs. Matched as whole crate names at the @@ -84,11 +85,17 @@ scan "engine (default features)" "$ENGINE_MANIFEST" # The model-pack verification crate runs at the Rust trust boundary and must be # network-free too (ed25519-dalek/sha2/serde have no network deps). scan "modelpack (default features)" "$MODELPACK_MANIFEST" +# Spike S5: llama.cpp (llama-cpp-2) linked next to the engine. `--target all` +# because llama-cpp-2 pulls extra llama-cpp-sys-2 features on Apple Silicon +# only, and `cargo tree` otherwise shows the host platform's graph alone. +# llama.cpp's own CMake build is outside `cargo tree`; see +# docs/spikes/s5-llm-packaging.md for how that was checked. +scan "spikes/s5-llama (llama.cpp + engine, all targets)" "$SPIKE_LLAMA_MANIFEST" --target all echo if [[ "$FAIL" -ne 0 ]]; then echo "FAIL: zero-egress gate tripped — a network crate is in the dependency graph." >&2 exit 1 fi -echo "PASS: zero-egress gate clean — no network crates in app, engine, or modelpack." +echo "PASS: zero-egress gate clean — no network crates in app, engine, modelpack, or the S5 llama spike." exit 0 diff --git a/spikes/s5-llama/.cargo/config.toml b/spikes/s5-llama/.cargo/config.toml new file mode 100644 index 0000000..f690103 --- /dev/null +++ b/spikes/s5-llama/.cargo/config.toml @@ -0,0 +1,20 @@ +# Applies when cargo runs from this directory (CI uses working-directory). +[env] +# CPU-only: ggml's CMake turns Metal on by default on Apple, and llama-cpp-2 +# enables llama-cpp-sys-2's `metal` feature on Apple Silicon regardless of our +# features. llama-cpp-sys-2 forwards GGML_* env vars to CMake, so this keeps the +# Metal backend out of the build (only the Metal framework link stays). +GGML_METAL = "OFF" +# llama-cpp-2 depends on llama-cpp-sys-2 with its DEFAULT features on every +# platform, so llama.cpp's `common` library and its vendored cpp-httplib (the +# model downloader's HTTP client) get compiled; cpp-httplib links OpenSSL (HTTPS) +# when CMake finds one (Homebrew's on a Mac, libssl-dev on a CI runner). Neither +# ends up in our binary (nothing references them), but keep HTTPS out of the +# build entirely. CMAKE_* env vars are forwarded to CMake as cache entries. +CMAKE_DISABLE_FIND_PACKAGE_OpenSSL = "TRUE" +# Windows (MSVC): sherpa-onnx's prebuilt archive is static-CRT (/MT), but +# llama-cpp-sys-2 builds llama.cpp with the DLL CRT (/MD) unless this is set, +# and the link then fails: "/failifmismatch: mismatch detected for +# 'RuntimeLibrary' ... MD_DynamicRelease ... MT_StaticRelease". Ignored on +# other targets. +LLAMA_STATIC_CRT = "1" diff --git a/spikes/s5-llama/.gitignore b/spikes/s5-llama/.gitignore new file mode 100644 index 0000000..9b4669d --- /dev/null +++ b/spikes/s5-llama/.gitignore @@ -0,0 +1 @@ +/target*/ diff --git a/spikes/s5-llama/Cargo.lock b/spikes/s5-llama/Cargo.lock new file mode 100644 index 0000000..a76d0f1 --- /dev/null +++ b/spikes/s5-llama/Cargo.lock @@ -0,0 +1,1919 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags 2.13.0", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.117", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + +[[package]] +name = "bzip2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" +dependencies = [ + "bzip2-sys", + "libc", +] + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + +[[package]] +name = "bzip2-sys" +version = "0.1.13+1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "cc" +version = "1.2.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", + "zeroize", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "engine" +version = "0.1.0" +dependencies = [ + "anyhow", + "hound", + "rubato", + "serde", + "serde_json", + "sherpa-onnx", + "symphonia", + "thiserror", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "find_cuda_helper" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f9e65c593dd01ac77daad909ea4ad17f0d6d1776193fc8ea766356177abdad" +dependencies = [ + "glob", +] + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "hound" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5314d1d545fce0307c770d791adf20d997e0b63b64e1ffeed8a920e290eabe4" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "llama-cpp-2" +version = "0.1.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e5249e590eab4a5015ba35cf078a4548b941e841ef8024310c3a10b2edb7179" +dependencies = [ + "enumflags2", + "llama-cpp-sys-2", + "thiserror", + "tracing", + "tracing-core", +] + +[[package]] +name = "llama-cpp-sys-2" +version = "0.1.161" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9bea77fde41bbc15a278891cd5edd2ba07c5260d162614b41080ba1f100b39b" +dependencies = [ + "bindgen", + "cc", + "cmake", + "find_cuda_helper", + "glob", + "walkdir", +] + +[[package]] +name = "log" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "lzma-rust2" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c46f3fcd2e888afdb01a07efc071cb21300e07c68d32c3e8b01b5c8cb1fcaa" +dependencies = [ + "sha2", +] + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "nix" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest", + "hmac", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppmd-rust" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd4acc8d264ea385db64ccfdcdfd5909ee9eda0975666723d59f3bfec80b3611" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.117", +] + +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "realfft" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677" +dependencies = [ + "rustfft", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rubato" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5258099699851cfd0082aeb645feb9c084d9a5e1f1b8d5372086b989fc5e56a1" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "realfft", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "s5-llama" +version = "0.0.0" +dependencies = [ + "engine", + "libc", + "llama-cpp-2", + "llama-cpp-sys-2", + "sherpa-onnx", + "windows-sys 0.59.0", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sherpa-onnx" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6956e34735af6efe416f5879181eee8e1b51be57dc6ce0a053691ae747114089" +dependencies = [ + "serde", + "serde_json", + "sherpa-onnx-sys", +] + +[[package]] +name = "sherpa-onnx-sys" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bc46e5fb3aab39141d48ad8763d0891e0b9e0fbc8e3bdefaa63704d1bf00054" +dependencies = [ + "bzip2 0.4.4", + "tar", + "ureq", + "zip", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-aac", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-isomp4", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-isomp4" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" +dependencies = [ + "encoding_rs", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.7", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zip" +version = "9.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec2e3161de27091f18a831d9494e9c53378a34833af5c1dda35ad85849da18d6" +dependencies = [ + "aes", + "bzip2 0.6.1", + "constant_time_eq", + "crc32fast", + "deflate64", + "flate2", + "getrandom 0.4.3", + "hmac", + "indexmap", + "lzma-rust2", + "memchr", + "nix", + "pbkdf2", + "ppmd-rust", + "sha1", + "time", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", + "zstd", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad5020ab8f27bfc0024ad0a07aed6bf022a16208f479686fbed4fdd0c85eb0b3" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9ea9cc2576c2fcc104e9cec04f46e3ede564f4fbc206831e4ef7e859a4140d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.3+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/spikes/s5-llama/Cargo.toml b/spikes/s5-llama/Cargo.toml new file mode 100644 index 0000000..1de1ca6 --- /dev/null +++ b/spikes/s5-llama/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "s5-llama" +version = "0.0.0" +edition = "2021" +publish = false +description = "Spike S5: link llama.cpp (llama-cpp-2) and sherpa-onnx (via engine) into one CPU-only binary. Throwaway; NOT linked into the app." +license = "Apache-2.0" + +[dependencies] +# The production engine (sherpa-onnx, static). Path dep, not a registry fetch. +engine = { path = "../../engine" } +# Same exact version the engine pins, so Cargo unifies it (no second copy). Used +# to call into the native sherpa-onnx / onnxruntime code directly. +sherpa-onnx = { version = "=2.0.1", default-features = false, features = ["static"] } + +# llama.cpp bindings, pinned EXACTLY (0.1.161 was published 2026-11-03; it +# vendors llama.cpp v0.6.0, commit d812350). default-features = false drops +# llama-cpp-2's `openmp` (ggml's own threadpool instead), `common` and +# `android-shared-stdcxx`. No GPU features. +# NOTE: llama-cpp-2 depends on llama-cpp-sys-2 WITH its default features, so the +# sys crate's `common` is on whatever we say here (llama.cpp's common library and +# its vendored cpp-httplib get compiled, but nothing links them into the binary), +# and on Apple Silicon it also turns on `metal`. .cargo/config.toml keeps Metal +# and OpenSSL out of the CMake build. +llama-cpp-2 = { version = "=0.1.161", default-features = false, optional = true } +llama-cpp-sys-2 = { version = "=0.1.161", default-features = false, optional = true } + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = ["Win32_System_ProcessStatus", "Win32_System_Threading", "Win32_Foundation"] } + +[features] +# `llama` off = the size/build-time baseline (sherpa-onnx only). +default = ["llama"] +llama = ["dep:llama-cpp-2", "dep:llama-cpp-sys-2"] + +[profile.release] +# Match a shipping build closely enough for size comparisons. +strip = "symbols" diff --git a/spikes/s5-llama/src/main.rs b/spikes/s5-llama/src/main.rs new file mode 100644 index 0000000..044bc26 --- /dev/null +++ b/spikes/s5-llama/src/main.rs @@ -0,0 +1,310 @@ +//! Spike S5: link llama.cpp (via `llama-cpp-2`) and sherpa-onnx (via the +//! production `engine` crate) into ONE CPU-only binary, then prove both native +//! runtimes start in the same process. +//! +//! Usage: +//! s5-llama --self-check +//! Starts sherpa-onnx/onnxruntime and the llama.cpp CPU backend, then exits +//! 0. No model needed (this is what CI runs on Windows, macOS and Linux). +//! s5-llama --model [--threads 4] [--n-predict 64] [--ctx 2048] +//! [--prompt "..."] [--vad ] +//! Loads the GGUF on the CPU and generates up to `--n-predict` tokens, +//! printing load time, prompt and generation tokens/s, and peak RSS. +//! `--vad` also runs a Silero VAD session through sherpa-onnx in the same +//! process first, so both runtimes have live threads and allocations. +//! +//! Throwaway spike code: not linked into the app. + +use std::path::PathBuf; +use std::time::Instant; + +struct Args { + self_check: bool, + model: Option, + vad: Option, + threads: i32, + n_predict: usize, + ctx: u32, + prompt: String, +} + +const DEFAULT_PROMPT: &str = + "Summarise in two sentences why a law firm might want transcription to run offline."; + +fn parse_args() -> Result { + let mut a = Args { + self_check: false, + model: None, + vad: None, + threads: 4, + n_predict: 64, + ctx: 2048, + prompt: DEFAULT_PROMPT.to_string(), + }; + let mut it = std::env::args().skip(1); + while let Some(flag) = it.next() { + let mut value = || it.next().ok_or_else(|| format!("{flag} needs a value")); + match flag.as_str() { + "--self-check" => a.self_check = true, + "--model" => a.model = Some(PathBuf::from(value()?)), + "--vad" => a.vad = Some(PathBuf::from(value()?)), + "--threads" => a.threads = value()?.parse().map_err(|e| format!("--threads: {e}"))?, + "--n-predict" => { + a.n_predict = value()?.parse().map_err(|e| format!("--n-predict: {e}"))? + } + "--ctx" => a.ctx = value()?.parse().map_err(|e| format!("--ctx: {e}"))?, + "--prompt" => a.prompt = value()?, + other => return Err(format!("unknown argument {other}")), + } + } + if !a.self_check && a.model.is_none() { + return Err("pass --self-check or --model ".into()); + } + Ok(a) +} + +/// Peak resident set size of this process, in MB (same method as asr-bench). +fn peak_rss_mb() -> Option { + #[cfg(unix)] + unsafe { + let mut u: libc::rusage = std::mem::zeroed(); + if libc::getrusage(libc::RUSAGE_SELF, &mut u) != 0 { + return None; + } + let raw = u.ru_maxrss as f64; + // macOS reports bytes, Linux kilobytes. + let bytes = if cfg!(target_os = "macos") { raw } else { raw * 1024.0 }; + Some(bytes / 1e6) + } + #[cfg(windows)] + unsafe { + use windows_sys::Win32::System::ProcessStatus::{ + GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); + c.cb = std::mem::size_of::() as u32; + if GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) == 0 { + return None; + } + Some(c.PeakWorkingSetSize as f64 / 1e6) + } + #[cfg(not(any(unix, windows)))] + None +} + +/// sherpa-onnx side: run native code in both sherpa-onnx and onnxruntime, and +/// go through the engine's real constructor (which references the full +/// recognizer/VAD/diarization graph, so the linker must resolve all of it). +fn sherpa_check() -> Result<(), String> { + println!( + "sherpa-onnx {} (git {}), onnxruntime {}", + sherpa_onnx::version(), + sherpa_onnx::git_sha1(), + sherpa_onnx::onnxruntime_version() + ); + let empty = std::env::temp_dir().join(format!("s5-llama-no-models-{}", std::process::id())); + let cfg = engine::EngineConfig::new(&empty); + match engine::SherpaEngine::new(&cfg) { + Ok(_) => return Err("SherpaEngine::new unexpectedly succeeded with no models".into()), + Err(e) => println!("engine: SherpaEngine::new without models fails closed as expected ({e})"), + } + println!( + "engine: {} model files required for the default config", + engine::required_model_files(cfg.asr_model, cfg.diarize).len() + ); + Ok(()) +} + +/// Run a real Silero VAD session through sherpa-onnx on one second of silence. +fn sherpa_vad(path: &std::path::Path) -> Result<(), String> { + let t = Instant::now(); + let mut silero = sherpa_onnx::SileroVadModelConfig::default(); + silero.model = Some(path.to_string_lossy().into_owned()); + silero.threshold = 0.5; + silero.min_silence_duration = 0.25; + silero.min_speech_duration = 0.25; + silero.max_speech_duration = 20.0; + silero.window_size = 512; + let cfg = sherpa_onnx::VadModelConfig { + silero_vad: silero, + ten_vad: Default::default(), + sample_rate: 16_000, + num_threads: 1, + provider: Some("cpu".to_string()), + debug: false, + }; + let vad = sherpa_onnx::VoiceActivityDetector::create(&cfg, 30.0) + .ok_or_else(|| format!("could not load VAD model {}", path.display()))?; + vad.accept_waveform(&vec![0.0f32; 16_000]); + vad.flush(); + println!( + "sherpa VAD: loaded {} and ran 1 s of silence in {:.0} ms (speech found: {})", + path.display(), + t.elapsed().as_secs_f64() * 1e3, + !vad.is_empty() + ); + Ok(()) +} + +#[cfg(feature = "llama")] +mod llama { + use super::{peak_rss_mb, Args}; + use llama_cpp_2::context::params::LlamaContextParams; + use llama_cpp_2::llama_backend::LlamaBackend; + use llama_cpp_2::llama_batch::LlamaBatch; + use llama_cpp_2::model::params::LlamaModelParams; + use llama_cpp_2::model::{LlamaChatMessage, LlamaModel}; + use llama_cpp_2::sampling::LlamaSampler; + use std::num::NonZeroU32; + use std::time::Instant; + + pub fn init() -> Result { + let mut backend = LlamaBackend::init().map_err(|e| format!("llama backend init: {e}"))?; + if std::env::var_os("S5_LLAMA_LOGS").is_none() { + backend.void_logs(); + } + Ok(backend) + } + + pub fn self_check(backend: &LlamaBackend) -> Result<(), String> { + let devices = llama_cpp_2::list_llama_ggml_backend_devices(); + let names: Vec = + devices.iter().map(|d| format!("{} ({})", d.name, d.backend)).collect(); + println!( + "llama.cpp: backend initialised; devices: [{}]; gpu offload supported: {}; mmap: {}", + names.join(", "), + backend.supports_gpu_offload(), + backend.supports_mmap() + ); + if devices.is_empty() { + return Err("llama.cpp registered no backend device".into()); + } + if devices.iter().any(|d| d.backend != "CPU") { + return Err("a non-CPU ggml backend is compiled in; the spike must be CPU-only".into()); + } + Ok(()) + } + + pub fn generate(backend: &LlamaBackend, a: &Args) -> Result<(), String> { + let path = a.model.as_ref().expect("checked by parse_args"); + let t_load = Instant::now(); + let mparams = LlamaModelParams::default().with_n_gpu_layers(0); + let model = LlamaModel::load_from_file(backend, path, &mparams) + .map_err(|e| format!("loading {}: {e}", path.display()))?; + let cparams = LlamaContextParams::default() + .with_n_ctx(NonZeroU32::new(a.ctx)) + // llama.cpp ABORTS the process (GGML_ASSERT) if one decode call gets + // more tokens than n_batch, so let the whole prompt fit. + .with_n_batch(a.ctx) + .with_n_threads(a.threads) + .with_n_threads_batch(a.threads); + let mut ctx = model + .new_context(backend, cparams) + .map_err(|e| format!("creating context: {e}"))?; + let load_s = t_load.elapsed().as_secs_f64(); + println!( + "llama.cpp: loaded {} ({:.2} GB, {:.2} B params) in {load_s:.2} s; peak RSS so far {:.0} MB", + path.display(), + model.size() as f64 / 1e9, + model.n_params() as f64 / 1e9, + peak_rss_mb().unwrap_or(f64::NAN) + ); + + // Use the model's own chat template when it has one. + let prompt = match model.chat_template(None) { + Ok(tmpl) => { + let msg = LlamaChatMessage::new("user".into(), a.prompt.clone()) + .map_err(|e| e.to_string())?; + model + .apply_chat_template(&tmpl, &[msg], true) + .map_err(|e| format!("chat template: {e}"))? + } + Err(_) => a.prompt.clone(), + }; + let vocab = model.vocab(); + let tokens = vocab.tokenize(prompt.as_bytes(), true, true); + let n_prompt = tokens.len(); + if n_prompt + a.n_predict >= a.ctx as usize { + return Err(format!( + "prompt ({n_prompt} tokens) + --n-predict does not fit in --ctx {}", + a.ctx + )); + } + + let mut batch = LlamaBatch::new(512.max(n_prompt), 1); + let last = n_prompt as i32 - 1; + for (i, tok) in tokens.iter().enumerate() { + batch + .add(*tok, i as i32, &[0], i as i32 == last) + .map_err(|e| e.to_string())?; + } + let t_prompt = Instant::now(); + ctx.decode(&mut batch).map_err(|e| format!("prompt decode: {e}"))?; + let prompt_s = t_prompt.elapsed().as_secs_f64(); + + let mut sampler = LlamaSampler::greedy(); + let mut out = Vec::::new(); + let mut n_cur = n_prompt as i32; + let mut n_gen = 0usize; + let t_gen = Instant::now(); + while n_gen < a.n_predict { + let tok = sampler.sample(&ctx, batch.n_tokens() - 1); + sampler.accept(tok); + if vocab.is_eog(tok) { + break; + } + out.extend(vocab.token_to_piece(tok, false, None)); + n_gen += 1; + batch.clear(); + batch.add(tok, n_cur, &[0], true).map_err(|e| e.to_string())?; + n_cur += 1; + ctx.decode(&mut batch).map_err(|e| format!("decode: {e}"))?; + } + let gen_s = t_gen.elapsed().as_secs_f64(); + + println!("--- output ---\n{}\n--------------", String::from_utf8_lossy(&out).trim()); + println!( + "RESULT threads={} load_s={load_s:.2} prompt_tokens={n_prompt} prompt_s={prompt_s:.3} prompt_tok_s={:.1} gen_tokens={n_gen} gen_s={gen_s:.3} gen_tok_s={:.1} peak_rss_mb={:.0}", + a.threads, + n_prompt as f64 / prompt_s, + n_gen as f64 / gen_s, + peak_rss_mb().unwrap_or(f64::NAN) + ); + Ok(()) + } +} + +fn run() -> Result<(), String> { + let a = parse_args()?; + sherpa_check()?; + if let Some(vad) = &a.vad { + sherpa_vad(vad)?; + } + + #[cfg(feature = "llama")] + { + let backend = llama::init()?; + llama::self_check(&backend)?; + if a.model.is_some() { + llama::generate(&backend, &a)?; + } + } + #[cfg(not(feature = "llama"))] + if a.model.is_some() { + return Err("built without the `llama` feature; rebuild with default features".into()); + } + + println!( + "OK: self-check passed; peak RSS {:.0} MB", + peak_rss_mb().unwrap_or(f64::NAN) + ); + Ok(()) +} + +fn main() { + if let Err(e) = run() { + eprintln!("ERROR: {e}"); + std::process::exit(1); + } +} From d56fd9bce9862f0f01637f031e2a0e1dd9e759d3 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Tue, 24 Nov 2026 22:50:56 +0000 Subject: [PATCH 03/10] docs(s5): packaging, licensing and zero-egress write-up GO-WITH-CONDITIONS. Adds the Qwen weights and llama.cpp rows to the third-party inventory (and fixes sherpa-onnx 1.13.2 -> 2.0.1), documents llm packs in model-packs.md, and marks S5 in the spike plan. --- docs/assurance/third-party-components.md | 21 +- docs/model-packs.md | 38 +++- docs/spikes/next-phase-spikes.md | 4 +- docs/spikes/s5-llm-packaging.md | 247 +++++++++++++++++++++++ 4 files changed, 307 insertions(+), 3 deletions(-) create mode 100644 docs/spikes/s5-llm-packaging.md diff --git a/docs/assurance/third-party-components.md b/docs/assurance/third-party-components.md index 140ebaf..ea9d405 100644 --- a/docs/assurance/third-party-components.md +++ b/docs/assurance/third-party-components.md @@ -39,11 +39,28 @@ All weights are MIT, Apache-2.0, or CC-BY-4.0 (attribution required), ungated, n the airplane-mode story. Models are bundled/imported as **signed model packs** verified before load (see `data-flow.md` and the modelpack section below). +## Language models (candidates from spike S5; not shipped yet) + +No language model ships in the app today. Spike S5 cleared these GGUF weights for +redistribution as signed `task: "llm"` model packs (see +`docs/spikes/s5-llm-packaging.md`). Both are ungated, need no token, and carry +plain Apache-2.0 with no use policy and no NOTICE file upstream. + +| Role | Model | Version / tag | Licence | Attribution (required) | +| --- | --- | --- | --- | --- | +| Notes (first choice) | Qwen3-4B-Instruct-2507, Q4_0 GGUF (quantised by Unsloth from `Qwen/Qwen3-4B-Instruct-2507`) | `unsloth/Qwen3-4B-Instruct-2507-GGUF` revision `a06e946`, file SHA-256 `e0ba675d…13be2` | **Apache-2.0** | Qwen Team, Alibaba Cloud ("Copyright 2024 Alibaba Cloud"); GGUF conversion and quantisation by Unsloth | +| Notes (alternative) | Qwen3.5-4B, Q4_0 GGUF, text weights only (quantised by Unsloth from `Qwen/Qwen3.5-4B`) | `unsloth/Qwen3.5-4B-GGUF` revision `e87f176`, file SHA-256 `298fcb5f…b72b8bb` | **Apache-2.0** | Qwen Team, Alibaba Cloud ("Copyright 2026 Alibaba Cloud"); GGUF conversion and quantisation by Unsloth | + +Redistributing either pack means: ship the Apache-2.0 licence text with it, keep the +Alibaba Cloud copyright line, say the weights were converted and quantised (a +modified form, section 4(b)), and don't use the Qwen name beyond describing where +the weights come from (section 6 grants no trademark rights). + ## Rust crates (the engine + app backend) | Crate | Version | Licence | Role | | --- | --- | --- | --- | -| `sherpa-onnx` (k2-fsa, official) | 1.13.2 | **Apache-2.0** | In-process ASR + `OfflineSpeakerDiarization`. (NOT the deprecated `sherpa-rs`.) | +| `sherpa-onnx` (k2-fsa, official) | 2.0.1 | **Apache-2.0** | In-process ASR + `OfflineSpeakerDiarization`. (NOT the deprecated `sherpa-rs`.) | | `symphonia` | 0.5.x | **MPL-2.0** | Pure-Rust audio demux/decode (mp3/AAC/FLAC/WAV/OGG). See note below. | | `rubato` | 0.16.x | **MIT** | Sample-rate conversion to 16 kHz. | | `hound` | 3.5.x | **Apache-2.0** | WAV read, and writing recordings made in the app. | @@ -59,6 +76,8 @@ verified before load (see `data-flow.md` and the modelpack section below). | `sha2` | 0.10.x | **Apache-2.0 / MIT** | Model-pack weights hashing. | | `base64` | 0.22.x | **Apache-2.0 / MIT** | Signature decoding. | | `zip` | 2.x | **MIT** | Extract verified model packs (a pack's `weights.bin` is a zip) into the per-user verified-models cache. | +| `llama-cpp-2` / `llama-cpp-sys-2` *(spike S5 only; not in the app)* | =0.1.161 | **MIT OR Apache-2.0** | Rust bindings to llama.cpp, for local notes (P2). Built from vendored sources, CPU only, default features off. | +| llama.cpp + ggml (C/C++, vendored in `llama-cpp-sys-2`) *(spike S5 only)* | v0.6.0 (commit `d812350`; ggml 0.26.0) | **MIT** | The LLM runtime, linked statically. Copyright the ggml authors. | > **`symphonia` licence note (MPL-2.0):** MPL-2.0 is a permissive, file-level > copyleft that is redistributable in a commercial product and does **not** diff --git a/docs/model-packs.md b/docs/model-packs.md index 749e96b..5420363 100644 --- a/docs/model-packs.md +++ b/docs/model-packs.md @@ -17,6 +17,27 @@ A pack is a directory of two files: `manifest.json` carries nine fields: `id`, `version`, `engine`, `engine_min_version`, `task`, `license`, `attribution`, `sha256`, and `signature`. +`task` is one of `asr`, `diarization` or `llm`; `engine` is one of `sherpa-onnx`, +`whisper.cpp` or `llama.cpp`. Packs are hashed and extracted as streams, so a +multi-GB pack never has to fit in memory. + +### Language-model packs (`task: "llm"`) + +An LLM pack carries one GGUF file for the `llama.cpp` engine. The signer stores +`.gguf` files in the zip **uncompressed** (they are already quantised; Deflate +would cost minutes of CPU for almost nothing), and everything else Deflated as +before. The app resolves an LLM pack separately from speech packs: speech +resolution never extracts an LLM pack, and `resolve_verified_llm` +(`app/src-tauri/src/models.rs`) returns the GGUF path only from a verified +`task: "llm"` pack, failing closed otherwise. Nothing in the app calls it yet; it +is groundwork for local notes (P2), measured in spike S5 +([`spikes/s5-llm-packaging.md`](spikes/s5-llm-packaging.md)). + +The `llama.cpp` engine version is llama.cpp's own release version (it uses semver +since v0.6.0). This build records **0.6.0**: the llama.cpp commit `d812350` that +`llama-cpp-sys-2 =0.1.161` vendors. An LLM pack should set +`--engine-min-version 0.6.0` until a newer llama.cpp is linked. + ## How verification works When you import a pack (or at transcription time), the verifier checks, in order, and @@ -63,6 +84,10 @@ from upstream [k2-fsa/sherpa-onnx](https://github.com/k2-fsa/sherpa-onnx) weight | `asr-whisper-medium.en` | asr | Whisper medium.en (int8) + Silero VAD | MIT | | `diarization-pyannote-campplus` | diarization | pyannote segmentation-3.0 + 3D-Speaker CAM++ | MIT AND Apache-2.0 | +No LLM pack ships yet. The candidate from spike S5 is `llm-qwen3-4b-instruct-2507` +(Qwen3-4B-Instruct-2507, Q4_0 GGUF from `unsloth/Qwen3-4B-Instruct-2507-GGUF`, +Apache-2.0, about 2.4 GB). + Upstream weights are fetched file by file from the sherpa-onnx Hugging Face repositories (`csukuangfj/…`) at fixed revisions — ungated, no token — except Silero VAD, which comes from the `asr-models` release tag of k2-fsa/sherpa-onnx (no sherpa-onnx Hugging Face @@ -96,7 +121,18 @@ cargo run --manifest-path tools/modelpack-sign/Cargo.toml -- pack \ (cd app && VENDOR_PUBKEY_SPKI_PEM="$(cat ../keys/public.spki.pem)" npm run tauri dev) ``` -The `pack` command self-verifies before writing, so a pack that's produced is guaranteed +An LLM pack is signed the same way, from a directory holding the one GGUF: + +```bash +cargo run --release --manifest-path tools/modelpack-sign/Cargo.toml -- pack \ + --model-dir --out llm-qwen3-4b-instruct-2507 --key keys/private.pkcs8.pem \ + --id llm-qwen3-4b-instruct-2507 --version 1.0.0 \ + --engine llama.cpp --engine-min-version 0.6.0 \ + --task llm --license Apache-2.0 \ + --attribution "Qwen3-4B-Instruct-2507 by the Qwen Team, Alibaba Cloud (Apache-2.0)" +``` + +The `pack` command self-verifies after writing, so a pack that's produced is guaranteed to pass the in-app verifier (with the matching key). To check an existing pack: ```bash diff --git a/docs/spikes/next-phase-spikes.md b/docs/spikes/next-phase-spikes.md index fef707d..7b10904 100644 --- a/docs/spikes/next-phase-spikes.md +++ b/docs/spikes/next-phase-spikes.md @@ -25,7 +25,7 @@ | **S2** | Can a local 3–4B LLM turn a **long transcript (15–90 min)** into a note fast enough on CPU? | 60-min transcript → note ≤ 5 min after stop; peak RAM ≤ 6 GB | 3 days | P2 | | **S3** | Can a small model **cite its sources** reliably, and how often does it fabricate? | ≥ 95% of note sentences have valid citations; 0 fabrications in blind review | 3 days | P3 | | **S4** | Does the local model **refuse or soften** safeguarding content? | 0 refusals, 0 softened facts on the sensitive set | 1 day | P2 (social care) | -| **S5** | Can we **package** llama.cpp + weights without breaking zero-egress or licensing? | Gate green; static build; licence-clean pick; signed pack verifies | 2 days | P2 | +| **S5** | Can we **package** llama.cpp + weights without breaking zero-egress or licensing? | Gate green; static build; licence-clean pick; signed pack verifies | 2 days | P2 — **go, with conditions** ([write-up](s5-llm-packaging.md)) | | **S6** | Is **crash-safe recording** simple and does "Delete transcript and audio" still purge everything? | ≤ 1 chunk lost on `kill`; full purge | 1 day | P1, assurance | | S7 | *(only if S1 fails)* Does **Nemotron Streaming** fix live lag on CPU? | Word lag ≤ 1 s at ≤ 60% CPU | 2 days | P1 fallback | | S8 | *(deferred to P4)* Can we capture **call audio** without echo or duplicates? | No duplicated or echoed text with speakers on | 3 days | P4 | @@ -137,6 +137,8 @@ hard gate for social-care templates.** ## S5: Packaging, licensing and zero-egress +> **Result: go, with conditions** (Mac; Windows cross-linked only; the new CI job still to run): see [`s5-llm-packaging.md`](s5-llm-packaging.md). Harness: `spikes/s5-llama/`. + **Question.** Can llama.cpp be linked in-process, built from vendored sources, and shipped with its weights as a signed model pack, without adding a network crate or a licence we can't redistribute? diff --git a/docs/spikes/s5-llm-packaging.md b/docs/spikes/s5-llm-packaging.md new file mode 100644 index 0000000..c43127e --- /dev/null +++ b/docs/spikes/s5-llm-packaging.md @@ -0,0 +1,247 @@ +# Spike S5: packaging, licensing and zero-egress for the local LLM + +> Status: **GO-WITH-CONDITIONS** (Mac measured; Windows cross-linked but not run; Linux, macOS and Windows CI +> still to run) · Recorded 2026-11-24. +> Plan: [`next-phase-spikes.md`](next-phase-spikes.md#s5-packaging-licensing-and-zero-egress). +> Harness: `spikes/s5-llama/` (one binary linking llama.cpp and the engine's sherpa-onnx). + +## Question + +Can llama.cpp be linked in-process, built from vendored sources, and shipped with its weights as a signed +model pack, without adding a network crate or a licence we can't redistribute? + +## Verdict + +Yes. llama.cpp and sherpa-onnx link into one static, CPU-only binary; the build needs no network; the +zero-egress gate stays green; a signed 2.4 GB Qwen3-4B pack verifies, resolves and loads in flat memory, and +fails closed after a one-byte change; and both candidate weights are plain Apache-2.0. + +| Pass criterion | Result | | +|---|---|---| +| Gate green | `scripts/check-no-network.sh` passes, now also scanning `spikes/s5-llama` on all targets | **Pass** | +| Reproducible static build, no build-time download | Mac: clean build with outbound network denied by the OS sandbox; two clean builds gave bit-identical binaries. Windows: links when cross-compiled (one setting needed, condition 2), not run. Linux: CI job written, not yet run | **Pass on Mac**; CI pending | +| Signed pack verifies and loads | `task: "llm"` pack signed, verified by the app's resolver, GGUF loaded and generating; one flipped byte rejected | **Pass** | +| Weights licence cleared | Qwen3-4B-Instruct-2507 and Qwen3.5-4B: Apache-2.0, ungated, no use policy, no NOTICE | **Pass** | + +**Conditions:** +1. **Turn off llama.cpp's `common` library properly before P2 ships.** `llama-cpp-2` depends on + `llama-cpp-sys-2` *with its default features*, so the sys crate's `common` feature is on whatever our + `Cargo.toml` says. That compiles llama.cpp's `common` library, which includes its model downloader and the + vendored `cpp-httplib` client; if CMake finds OpenSSL (Homebrew on a Mac, `libssl-dev` on CI runners), the + client is built with HTTPS. None of it reaches our binary, because nothing references it (checked below), + and `cargo tree` can't see any of it. The spike sets `CMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE` so HTTPS + is never built. For the product, patch `llama-cpp-2` (a `[patch.crates-io]` copy whose `llama-cpp-sys-2` + dependency has `default-features = false`), or send that one-line fix upstream, and add a binary-level + check to the gate (below). +2. **Windows needs `LLAMA_STATIC_CRT=1`.** sherpa-onnx's Windows archive is built with the static CRT (`/MT`); + `llama-cpp-sys-2` builds llama.cpp with the DLL CRT (`/MD`) unless that variable is set, and the link fails: + `lld-link: error: /failifmismatch: mismatch detected for 'RuntimeLibrary': … llama.cpp.obj has value + MD_DynamicRelease … c-api.obj has value MT_StaticRelease`. With it set, the cross-compiled `.exe` links and + imports only Windows system DLLs. The spike sets it in `spikes/s5-llama/.cargo/config.toml`; the app will + need the same. +3. **Run the new CI job** (`s5-llama` in `.github/workflows/ci.yml`) on Linux, macOS and Windows after push. + It has not run yet. The Linux leg builds inside a network namespace with no network, which is the + CI-side proof of "no build-time download". +4. **Validate llama.cpp inputs before calling it.** llama.cpp **aborts the process** on misuse instead of + returning an error: the first long-prompt run here died on `GGML_ASSERT(n_tokens_all <= cparams.n_batch)`. + Inside the app that kills the whole app, so P2's wrapper must check prompt length against `n_batch`/`n_ctx` + (or run the LLM in a child process). +5. **Decide the LLM pack layout for P2.** The spike keeps the existing pack format (a zip in `weights.bin`, + with the GGUF Stored). That costs a second 2.4 GB copy on disk (pack plus extracted GGUF) and the + extracted copy is trusted from the cache without being re-hashed (the speech packs work the same way). Since + a Stored zip gains nothing for one file, consider letting an `llm` pack's `weights.bin` *be* the GGUF: + verify it, then load it in place. + +## Environment + +- **Machine:** Apple M5 Pro (18 cores, 48 GB), macOS 27.2. Not the reference laptop. **Heavily loaded:** + other spikes were running two `llama-server` processes (about 430% CPU each), so the load average was + 52–130 during the builds and first timings and about 16 during the later timings. Wall-clock build times + are noisy; CPU time (user + sys) is the steadier figure. +- **Toolchain:** rustc 1.99.1; CMake 4.5.1 and Ninja 1.13.2 (Homebrew, installed for this spike); Apple + clang; for Windows, `cargo-xwin` 0.23.1 with Homebrew LLVM and the cached Windows SDK. +- **Crates:** `llama-cpp-2 =0.1.161` and `llama-cpp-sys-2 =0.1.161` (published 2026-11-03, 21 days before the + spike), default features off, no GPU feature. The sys crate vendors **llama.cpp v0.6.0** (commit + `d812350`, 2026-10-05; ggml 0.26.0), which is the `llama.cpp` engine version recorded for packs. + `sherpa-onnx =2.0.1` (onnxruntime 1.28.2), the same version the engine pins. +- **Build settings** (`spikes/s5-llama/.cargo/config.toml`): `GGML_METAL=OFF` (CPU only; llama-cpp-2 turns on + the sys crate's `metal` feature on Apple Silicon, so only the Metal framework link remains), + `CMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `LLAMA_STATIC_CRT=1`. `GGML_OPENMP` is off (no OpenMP runtime to + clash with onnxruntime's threads), `GGML_NATIVE` off, `LLAMA_CURL` off. +- **Weights:** `Qwen3-4B-Instruct-2507-Q4_0.gguf` (2,375,773,280 bytes, SHA-256 `e0ba675d…13be2`, matching the + Hugging Face LFS hash of `unsloth/Qwen3-4B-Instruct-2507-GGUF`) and `Qwen3.5-4B-Q4_0.gguf` (`298fcb5f…b72b8bb`, + matching `unsloth/Qwen3.5-4B-GGUF`). + +## Commands + +```bash +cd spikes/s5-llama +cargo fetch +# sherpa-onnx's build script downloads its static libs unless pointed at them; here the extracted +# official sherpa-onnx-v2.0.1-osx-arm64-static-lib archive from an earlier engine build: +export SHERPA_ONNX_LIB_DIR=…/sherpa-onnx-v2.0.1-osx-arm64-static-lib/lib + +# Clean builds with outbound network denied by the macOS sandbox (curl fails inside it): +sandbox-exec -p '(version 1)(allow default)(deny network-outbound (remote ip))' \ + cargo build --offline --release --target-dir target-sandbox +sandbox-exec -p '(version 1)(allow default)(deny network-outbound (remote ip))' \ + cargo build --offline --release --no-default-features --target-dir target-nollama + +./target-sandbox/release/s5-llama --self-check +/usr/bin/time -l ./target-sandbox/release/s5-llama --model Qwen3-4B-Instruct-2507-Q4_0.gguf \ + --threads 4 --n-predict 64 --prompt "$(python3 prompt.py)" --vad silero_vad.onnx + +# Windows cross-check (scripts/build-windows-on-mac.sh has the one-time setup): +cargo xwin build --release --target x86_64-pc-windows-msvc --target-dir target-xwin + +# Real pack, with a throwaway key (never committed): +modelpack-sign keygen --out-dir /tmp/s5/keys +modelpack-sign pack --model-dir /tmp/s5/model --out /tmp/s5/packs/llm-qwen3-4b-instruct-2507 \ + --key /tmp/s5/keys/private.pkcs8.pem --id llm-qwen3-4b-instruct-2507 --version 1.0.0 \ + --engine llama.cpp --engine-min-version 0.6.0 --task llm --license Apache-2.0 \ + --attribution "Qwen3-4B-Instruct-2507 by the Qwen Team, Alibaba Cloud (Apache-2.0); GGUF Q4_0 by Unsloth" +modelpack-sign verify --pack /tmp/s5/packs/llm-qwen3-4b-instruct-2507 --pubkey /tmp/s5/keys/public.spki.pem +``` + +`prompt.py` printed a 24-line synthetic housing-visit transcript with an instruction to list its facts (730 +tokens with Qwen3's chat template). The app-side resolve was measured with a temporary, uncommitted `#[ignore]` +test calling `resolve_verified_llm_in` on the real pack, run under `/usr/bin/time -l`. "Before" numbers come +from `main`'s `tools/modelpack-sign`, built from `git archive main`. + +## No build-time download + +- **`llama-cpp-sys-2`'s `build.rs`** runs bindgen on the vendored headers and CMake on the vendored + `llama.cpp/` tree. It sets `LLAMA_CURL=OFF` and turns tests, examples, tools, server and the `llama` app off. + It has no download code of its own. +- **Every download path in the vendored CMake is off by default and stays off:** KleidiAI (`GGML_CPU_KLEIDIAI`, + OFF), the Windows LLVM OpenMP fetch (`GGML_OPENMP_FETCH`, OFF; OpenMP is off too), and BoringSSL/LibreSSL + `FetchContent` inside `vendor/cpp-httplib` (only reached through `common`, condition 1, and only with options + we don't set). +- **Proof:** the clean Mac build above ran with outbound IP traffic denied and `--offline`, and succeeded. The + CMake cache shows `GGML_METAL=OFF`, `GGML_OPENMP=OFF`, `GGML_NATIVE=OFF`, `GGML_CPU_KLEIDIAI=OFF`; the build + log has no "OpenSSL found" line. +- **Reproducible:** two clean builds into different target directories, one sandboxed and one not, produced + byte-identical binaries (SHA-256 `fcf1d661…72fb`). +- **What reaches the binary:** the link line has `ggml-base`, `ggml-cpu`, `ggml`, `llama`, `llama-common`, + `llama-common-base` (static) plus system frameworks; no `cpp-httplib`, no OpenSSL. `otool -L` lists only + system libraries; `strings` finds no `httplib`, `User-Agent` or download URLs, only GGUF metadata key names. + `libllama-common.a` does contain the downloader (34 `download` symbols) but the linker pulls none of it. +- **Blind spots of the gate this spike found:** `cargo tree -e normal` doesn't show build dependencies + (sherpa-onnx-sys compiles `ureq` and `rustls` into its build script, which the offline build never runs), and + it can't see anything CMake builds. The new CI job's no-network Linux build covers both; a cheap addition + would be a binary-level check in the gate (imports and strings of the release binary). + +## Raw numbers + +### Build and size (Mac, release, `strip = "symbols"`) + +| Build | Wall time | CPU time (user + sys) | Load average | Binary | +|---|---:|---:|---|---:| +| engine only (`--no-default-features`) | 40 s | 99 s | high | 16,986,704 B | +| engine only, sandboxed | 97 s | 96 s | 95–130 | 16,986,704 B | +| engine + llama.cpp | 7 min 40 s | 334 s | high | 20,616,816 B | +| engine + llama.cpp, sandboxed | 8 min 35 s | 313 s | 52–94 | 20,616,816 B | + +llama.cpp adds **about 3.6 MB (+21%)** to the binary and **about 220–240 s of CPU time** to a clean build, +almost all of it the CMake build of llama.cpp. Windows (cross-compiled with `cargo xwin`): 18,067,968 B +without llama.cpp, 22,466,048 B with it (**+4.4 MB, +24%**). The `.exe` imports `kernel32`, `ntdll`, +`ADVAPI32`, `psapi`, `dbghelp`, `setupapi`, `dxgi` and two `api-ms-win-core` sets: no CRT DLL. + +### Both runtimes in one process + +`--self-check` prints sherpa-onnx 2.0.1 / onnxruntime 1.28.2, runs `SherpaEngine::new` (fails closed with no +models, as it should), starts the llama.cpp backend (devices: `CPU` only) and exits 0, at 10 MB peak RSS. +`--vad` also runs a real Silero VAD session through sherpa-onnx (52 ms for 1 s of audio) before llama.cpp +loads. No duplicate symbols, no thread-pool clash. + +### Generation, Qwen3-4B-Instruct-2507 Q4_0, 4 threads, CPU, 2k context, greedy + +| Run | Load avg | Load | Prompt (730 tok) | Generation (64 tok) | Peak footprint | Peak RSS | +|---|---|---:|---:|---:|---:|---:| +| 1 | 52 | 1.78 s | 52.1 tok/s | 17.6 tok/s | 2.77 GB | 4.90 GB | +| 2 | 52 | 1.23 s | 52.2 tok/s | 20.7 tok/s | 2.77 GB | 5.13 GB | +| 3 | 72 | 1.26 s | 45.2 tok/s | 21.2 tok/s | 2.77 GB | 5.13 GB | +| 4 | 16 | 1.48 s | 101.8 tok/s | 34.0 tok/s | 2.77 GB | 5.14 GB | +| 5 | 16 | 0.80 s | 99.2 tok/s | 27.9 tok/s | 2.77 GB | 5.14 GB | +| 6 | 16 | 0.96 s | 92.0 tok/s | 28.1 tok/s | 2.76 GB | 5.14 GB | + +Every run also ran the Silero VAD session through sherpa-onnx first. Qwen3.5-4B Q4_0, same prompt (754 tokens) at load 16: load +2.03 s, prompt 81.5 tok/s, generation 26.0 tok/s, footprint 2.83 GB. Load times are with the GGUF in the page +cache. "Peak footprint" is macOS's physical footprint; RSS also counts the memory-mapped GGUF pages and so +overstates real use (S2 saw the same). The loaded-machine figures match S2's medians (prefill 53, generation 16 +tok/s for Qwen3-4B). + +### The real pack + +| Step | `main` (whole file in RAM, Deflate) | This branch (streamed, GGUF Stored) | +|---|---|---| +| Pack size | 2,274,469,097 B (Deflate saves 4.3%) | 2,375,773,442 B (GGUF + 162 B) | +| Sign (`pack`) | 66.5 s, **4.66 GB** peak footprint | 19.7 s, **3.7 MB** peak footprint | +| Verify (`verify`) | 6.25 s, **2.28 GB** | 6.52 s, **2.6 MB** | +| App resolve, first (verify + extract) | — | 8.65 s, 3.5 MB footprint (10.9 MB RSS) | +| App resolve, cache hit (verify only) | — | 6.16 s | + +`main` can't sign a `task: "llm"` pack, so its numbers are for the same GGUF signed as `task: "asr"`; its +verifier rejects the new pack (`manifest engine "llama.cpp" is not one of: whisper.cpp, sherpa-onnx`), so older +apps fail closed on LLM packs. The extracted GGUF hashed to the original's `e0ba675d…` and loaded and +generated in the spike binary. After flipping the byte at offset 1,000,000,000 of `weights.bin`, the app +resolver returned `no verified LLM model pack found` and `modelpack-sign verify` printed `REJECTED: weights +hash mismatch (tampered or corrupt)`. + +Disk use per installed LLM is about 4.75 GB: the 2.38 GB pack plus the 2.38 GB extracted GGUF (condition 5). +Re-verifying the pack costs about 6 s of hashing each time it is resolved. + +## Licences + +| Component | Licence | Redistribution | Attribution / notices | Use restrictions | +|---|---|---|---|---| +| Qwen3-4B-Instruct-2507 (`Qwen/Qwen3-4B-Instruct-2507`, rev `cdbee75`) | Apache-2.0 (LICENSE in repo, "Copyright 2024 Alibaba Cloud") | Allowed, including modified forms | Keep the licence and copyright line, mark the GGUF as modified (converted, quantised). No NOTICE file | None. Ungated, no acceptable-use policy | +| GGUF `unsloth/Qwen3-4B-Instruct-2507-GGUF` (rev `a06e946`) | Card says Apache-2.0, linking Qwen's LICENSE; the repo has no LICENSE of its own | Same terms as upstream | Credit Unsloth for the conversion | None | +| Qwen3.5-4B (`Qwen/Qwen3.5-4B`, rev `851bf6e`; base `Qwen3.5-4B-Base`) | Apache-2.0 ("Copyright 2026 Alibaba Cloud") | Allowed | As above. No NOTICE file | None. Ungated. The model is multimodal; the Q4_0 GGUF is the text model only | +| GGUF `unsloth/Qwen3.5-4B-GGUF` (rev `e87f176`) | Card says Apache-2.0, linking Qwen's LICENSE | Same | Credit Unsloth | None | +| llama.cpp + ggml v0.6.0 | MIT ("Copyright (c) 2023-2026 The ggml authors") | Allowed | Ship the MIT notice | None | +| `llama-cpp-2`, `llama-cpp-sys-2` 0.1.161 | MIT OR Apache-2.0 | Allowed | Licence text | None | + +Apache-2.0 gives no trademark rights (section 6), so the app can say "Qwen3-4B-Instruct-2507 by the Qwen Team" +but shouldn't brand anything as Qwen. The rows are in `docs/assurance/third-party-components.md`. + +## Pack support added on this branch + +- `modelpack` (Rust) and `core/src/modelpack.ts` accept `task: "llm"` and `engine: "llama.cpp"`. The + conformance fixtures gained a `valid-llm` case; `context.json` gives `llama.cpp` version 0.6.0. +- `modelpack` hashes weights from a stream in 1 MiB chunks (`verify_model_pack_reader`, `sha256_hex_file`); + `verify_model_pack` over a byte slice still works as before. +- `modelpack-sign` has `--task llm`, zips straight into `weights.bin` (each file streamed in; `.gguf` Stored, + everything else Deflated as before; zip64 for files of 4 GiB or more), hashes and self-verifies by streaming, + and knows `llama.cpp` 0.6.0. +- The app (`app/src-tauri/src/models.rs`) verifies and extracts packs by streaming, keeps LLM packs out of the + speech-model cache, and has `resolve_verified_llm_in` / `resolve_verified_llm`, which return the GGUF path + from the newest verified `llm` pack and fail closed otherwise. Nothing calls them yet. +- Tests (the agreed list): the `valid-llm` and unknown-task conformance cases (Rust and TS); `--task llm` + through the real CLI producing a pack the verifier accepts; the app resolving a signed LLM fixture pack to + its GGUF, rejecting a tampered one, and never returning a speech pack as an LLM; and a streamed hash of a + file larger than one chunk against a `shasum`-computed literal. + +## What changes in the PRD + +- **Runtime:** name the binding and version: `llama-cpp-2 =0.1.161` (llama.cpp v0.6.0), default features off, + `GGML_METAL=OFF`, `LLAMA_STATIC_CRT=1`, OpenMP off, and the `common` fix from condition 1. JSON-schema to + grammar conversion (`json_schema_to_grammar`) needs `common`; for P3 prefer GBNF grammars given directly to + `LlamaSampler::grammar`, which works without it. +- **Delivery:** the pack manifest gains `task: "llm"` and `engine: "llama.cpp"` (done here), and resolution + uses `resolve_verified_llm`, not `resolve_verified_models_dir`, which now ignores LLM packs. Decide the pack + layout (condition 5). +- **Sizes:** the app binary grows by about 4 MB; the LLM pack is about 2.4 GB to download and 4.75 GB on disk + as built here. Memory for Qwen3-4B Q4_0 at a 2k context is about 2.8 GB physical (S2 measured 4.4–4.7 GB at 8k + context with the S2 setup). +- **Install paths:** the per-user NSIS install is unaffected (packs live in per-user app data). There is no + MSI target yet, so the plan's MSI check doesn't apply. + +## Still to do + +- Run the `s5-llama` CI job on all three platforms, including the no-network Linux build, and run the + Windows binary (only cross-linked here). +- Repeat the generation timings on the reference Windows laptop, ideally with the app's live ASR running. +- Build a release installer with llama.cpp linked to measure its size (only the binary was measured). +- The signer's self-check still knows sherpa-onnx as 1.13.2 while the app ships 2.0.1, so it would refuse a + pack with `--engine-min-version 2.0.1`. This predates S5 and is left as it was. From e20dad0e827e842140a1f165610b81af4e556b91 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 08:35:39 +0000 Subject: [PATCH 04/10] spike(s5): set CMAKE_MSVC_RUNTIME_LIBRARY so llama.cpp uses the static CRT on real MSVC windows-latest CI failed with the RuntimeLibrary MD/MT mismatch: LLAMA_STATIC_CRT only adds /MT flags, and llama.cpp's CMake (policy CMP0091) takes the runtime from CMAKE_MSVC_RUNTIME_LIBRARY instead. --- docs/spikes/s5-llm-packaging.md | 12 +++++++----- spikes/s5-llama/.cargo/config.toml | 7 +++++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/spikes/s5-llm-packaging.md b/docs/spikes/s5-llm-packaging.md index c43127e..40d5c41 100644 --- a/docs/spikes/s5-llm-packaging.md +++ b/docs/spikes/s5-llm-packaging.md @@ -33,11 +33,13 @@ fails closed after a one-byte change; and both candidate weights are plain Apach is never built. For the product, patch `llama-cpp-2` (a `[patch.crates-io]` copy whose `llama-cpp-sys-2` dependency has `default-features = false`), or send that one-line fix upstream, and add a binary-level check to the gate (below). -2. **Windows needs `LLAMA_STATIC_CRT=1`.** sherpa-onnx's Windows archive is built with the static CRT (`/MT`); - `llama-cpp-sys-2` builds llama.cpp with the DLL CRT (`/MD`) unless that variable is set, and the link fails: - `lld-link: error: /failifmismatch: mismatch detected for 'RuntimeLibrary': … llama.cpp.obj has value - MD_DynamicRelease … c-api.obj has value MT_StaticRelease`. With it set, the cross-compiled `.exe` links and - imports only Windows system DLLs. The spike sets it in `spikes/s5-llama/.cargo/config.toml`; the app will +2. **Windows needs llama.cpp built with the static CRT, through CMake.** sherpa-onnx's Windows archive is built + with the static CRT (`/MT`); llama.cpp builds with the DLL CRT (`/MD`) by default, and the link fails: + `mismatch detected for 'RuntimeLibrary': … MD_DynamicRelease … MT_StaticRelease`. `LLAMA_STATIC_CRT=1` + alone was enough for the `cargo xwin` cross-build, but not on `windows-latest` with real MSVC: llama.cpp's + `cmake_minimum_required(... 3.28)` turns on CMake policy CMP0091, so the runtime comes from + `CMAKE_MSVC_RUNTIME_LIBRARY` (default `MultiThreaded…DLL`) and the `/MT` flags are overridden. The spike now + also sets `CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded` in `spikes/s5-llama/.cargo/config.toml`; the app will need the same. 3. **Run the new CI job** (`s5-llama` in `.github/workflows/ci.yml`) on Linux, macOS and Windows after push. It has not run yet. The Linux leg builds inside a network namespace with no network, which is the diff --git a/spikes/s5-llama/.cargo/config.toml b/spikes/s5-llama/.cargo/config.toml index f690103..ccd9f72 100644 --- a/spikes/s5-llama/.cargo/config.toml +++ b/spikes/s5-llama/.cargo/config.toml @@ -18,3 +18,10 @@ CMAKE_DISABLE_FIND_PACKAGE_OpenSSL = "TRUE" # 'RuntimeLibrary' ... MD_DynamicRelease ... MT_StaticRelease". Ignored on # other targets. LLAMA_STATIC_CRT = "1" +# LLAMA_STATIC_CRT only adds /MT compiler flags (cmake-rs `static_crt`). With +# real MSVC, llama.cpp's `cmake_minimum_required(... 3.28)` turns on CMake +# policy CMP0091, so the runtime comes from CMAKE_MSVC_RUNTIME_LIBRARY, which +# defaults to the DLL runtime (/MD). The cross-build with clang-cl linked +# anyway; windows-latest CI failed with the same RuntimeLibrary mismatch. Set +# the CMake variable too (llama-cpp-sys-2 forwards CMAKE_* env vars). +CMAKE_MSVC_RUNTIME_LIBRARY = "MultiThreaded" From d2ec87e06bcad88457f2d727fabf451855923a43 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 08:44:24 +0000 Subject: [PATCH 05/10] docs(s5): CI is green on Linux, macOS and Windows; condition 3 updated --- docs/spikes/s5-llm-packaging.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/spikes/s5-llm-packaging.md b/docs/spikes/s5-llm-packaging.md index 40d5c41..1f642e4 100644 --- a/docs/spikes/s5-llm-packaging.md +++ b/docs/spikes/s5-llm-packaging.md @@ -1,7 +1,7 @@ # Spike S5: packaging, licensing and zero-egress for the local LLM -> Status: **GO-WITH-CONDITIONS** (Mac measured; Windows cross-linked but not run; Linux, macOS and Windows CI -> still to run) · Recorded 2026-11-24. +> Status: **GO-WITH-CONDITIONS** (Mac measured; CI green on Linux with no network, macOS and Windows, where the +> binary runs a self-check without a model) · Recorded 2026-11-24. > Plan: [`next-phase-spikes.md`](next-phase-spikes.md#s5-packaging-licensing-and-zero-egress). > Harness: `spikes/s5-llama/` (one binary linking llama.cpp and the engine's sherpa-onnx). @@ -19,7 +19,7 @@ fails closed after a one-byte change; and both candidate weights are plain Apach | Pass criterion | Result | | |---|---|---| | Gate green | `scripts/check-no-network.sh` passes, now also scanning `spikes/s5-llama` on all targets | **Pass** | -| Reproducible static build, no build-time download | Mac: clean build with outbound network denied by the OS sandbox; two clean builds gave bit-identical binaries. Windows: links when cross-compiled (one setting needed, condition 2), not run. Linux: CI job written, not yet run | **Pass on Mac**; CI pending | +| Reproducible static build, no build-time download | Mac: clean build with outbound network denied by the OS sandbox; two clean builds gave bit-identical binaries. Linux (CI): builds inside a network namespace with no network. Windows (CI, real MSVC): links once condition 2's CMake setting is in, and the self-check runs | **Pass** | | Signed pack verifies and loads | `task: "llm"` pack signed, verified by the app's resolver, GGUF loaded and generating; one flipped byte rejected | **Pass** | | Weights licence cleared | Qwen3-4B-Instruct-2507 and Qwen3.5-4B: Apache-2.0, ungated, no use policy, no NOTICE | **Pass** | @@ -41,9 +41,11 @@ fails closed after a one-byte change; and both candidate weights are plain Apach `CMAKE_MSVC_RUNTIME_LIBRARY` (default `MultiThreaded…DLL`) and the `/MT` flags are overridden. The spike now also sets `CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded` in `spikes/s5-llama/.cargo/config.toml`; the app will need the same. -3. **Run the new CI job** (`s5-llama` in `.github/workflows/ci.yml`) on Linux, macOS and Windows after push. - It has not run yet. The Linux leg builds inside a network namespace with no network, which is the - CI-side proof of "no build-time download". +3. **Keep the `s5-llama` CI job (or its equivalent for the app) green.** On its first run it caught condition + 2 on real MSVC, which the cross-build had hidden. It now passes on all three: the Linux leg builds inside a + network namespace with no network (the CI-side proof of "no build-time download"), and on Windows the binary + runs its self-check (sherpa-onnx 2.0.1 / onnxruntime 1.28.2 plus the llama.cpp backend in one process). No + model has been loaded on Windows yet; that is for the reference laptop. 4. **Validate llama.cpp inputs before calling it.** llama.cpp **aborts the process** on misuse instead of returning an error: the first long-prompt run here died on `GGML_ASSERT(n_tokens_all <= cparams.n_batch)`. Inside the app that kills the whole app, so P2's wrapper must check prompt length against `n_batch`/`n_ctx` From 17b24535bc5c6e8e2002fa72e63083b1b6248439 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 09:51:28 +0000 Subject: [PATCH 06/10] modelpack: an llm pack must name llama.cpp, and llama.cpp runs only llm Both validators (Rust and TS) accepted task "llm" with engine "sherpa-onnx", so a pack could pass the engine-version gate for one runtime and be handed to another. New conformance case malformed-llm-wrong-engine. --- core/src/modelpack.ts | 5 +++++ fixtures/modelpack/README.md | 1 + .../cases/malformed-llm-wrong-engine/expected.json | 4 ++++ .../cases/malformed-llm-wrong-engine/manifest.json | 11 +++++++++++ modelpack/src/lib.rs | 11 +++++++++++ scripts/gen-modelpack-fixtures.ts | 10 ++++++++++ 6 files changed, 42 insertions(+) create mode 100644 fixtures/modelpack/cases/malformed-llm-wrong-engine/expected.json create mode 100644 fixtures/modelpack/cases/malformed-llm-wrong-engine/manifest.json diff --git a/core/src/modelpack.ts b/core/src/modelpack.ts index 18ccc8a..fdfa20e 100644 --- a/core/src/modelpack.ts +++ b/core/src/modelpack.ts @@ -171,6 +171,11 @@ export function validateManifest(obj: unknown): ValidateResult { reason: `manifest task "${m.task}" is not one of: ${TASKS.join(", ")}`, }; } + // A language model runs only on llama.cpp, and llama.cpp runs nothing else, + // so a pack can't pass the engine check for one runtime and be loaded by another. + if ((m.task === "llm") !== (m.engine === "llama.cpp")) { + return { ok: false, reason: `manifest task "${m.task}" cannot run on engine "${m.engine}"` }; + } if (!SEMVER_RE.test(m.version as string)) { return { ok: false, reason: `manifest version "${m.version as string}" is not valid semver (expected x.y.z)` }; diff --git a/fixtures/modelpack/README.md b/fixtures/modelpack/README.md index 13b3e93..4f6dfe8 100644 --- a/fixtures/modelpack/README.md +++ b/fixtures/modelpack/README.md @@ -64,3 +64,4 @@ are fixed in the script). It rewrites `cases/` and `context.json` only. | `malformed-uppercase-sha256` | reject | uppercase hex sha256 rejected (lowercase only) | | `malformed-unknown-engine` | reject | engine not in the allowed set | | `malformed-unknown-task` | reject | task not in the allowed set | +| `malformed-llm-wrong-engine` | reject | `task: "llm"` only runs on `llama.cpp` (and `llama.cpp` only runs `llm`) | diff --git a/fixtures/modelpack/cases/malformed-llm-wrong-engine/expected.json b/fixtures/modelpack/cases/malformed-llm-wrong-engine/expected.json new file mode 100644 index 0000000..f05bfc0 --- /dev/null +++ b/fixtures/modelpack/cases/malformed-llm-wrong-engine/expected.json @@ -0,0 +1,4 @@ +{ + "outcome": "reject", + "reasonContains": "cannot run on engine" +} diff --git a/fixtures/modelpack/cases/malformed-llm-wrong-engine/manifest.json b/fixtures/modelpack/cases/malformed-llm-wrong-engine/manifest.json new file mode 100644 index 0000000..258248d --- /dev/null +++ b/fixtures/modelpack/cases/malformed-llm-wrong-engine/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "acme/whisper-base-en", + "version": "1.2.3", + "engine": "sherpa-onnx", + "engine_min_version": "1.5.0", + "task": "llm", + "license": "MIT", + "attribution": "Acme Speech Labs", + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "signature": "AA==" +} diff --git a/modelpack/src/lib.rs b/modelpack/src/lib.rs index da7b936..8cd6547 100644 --- a/modelpack/src/lib.rs +++ b/modelpack/src/lib.rs @@ -44,6 +44,10 @@ pub const ENGINES: [&str; 3] = ["whisper.cpp", "sherpa-onnx", "llama.cpp"]; /// Tasks a model pack can perform (mirrors `TASKS` in the TS). pub const TASKS: [&str; 3] = ["asr", "diarization", "llm"]; +/// The task of a language-model pack, and the only engine that runs it. +const LLM_TASK: &str = "llm"; +const LLM_ENGINE: &str = "llama.cpp"; + /// A validated model-pack manifest. Field NAMES match the TS interface; the /// declared field ORDER here is the canonical sorted order so that /// [`canonicalize`] is byte-identical to the TS `canonicalize`. @@ -195,6 +199,13 @@ pub fn validate_manifest(value: &Value) -> Result { TASKS.join(", ") )); } + // A language model runs only on llama.cpp, and llama.cpp runs nothing else, + // so a pack can't pass the engine check for one runtime and be loaded by another. + if (task == LLM_TASK) != (engine == LLM_ENGINE) { + return Err(format!( + "manifest task \"{task}\" cannot run on engine \"{engine}\"" + )); + } let version = m.get("version").and_then(Value::as_str).unwrap_or(""); if !is_semver(version) { diff --git a/scripts/gen-modelpack-fixtures.ts b/scripts/gen-modelpack-fixtures.ts index 17ba3e8..aff3386 100644 --- a/scripts/gen-modelpack-fixtures.ts +++ b/scripts/gen-modelpack-fixtures.ts @@ -275,4 +275,14 @@ function baseManifest(overrides: Record = {}): Record Date: Wed, 25 Nov 2026 09:51:28 +0000 Subject: [PATCH 07/10] app: skip LLM packs before hashing them for speech; this build verifies no LLM pack - Speech resolution verified every pack, LLM included, before dropping LLM packs: a 2.4 GB pack added ~6 s of hashing to every recording start. The manifest's declared task now decides which packs are verified at all (a forged task can only make a pack be skipped). - engine_versions() no longer lists llama.cpp, which this build doesn't link, so a signed LLM pack shows as "engine not supported by this build" instead of verified. --- app/src-tauri/src/models.rs | 101 ++++++++++++++++++++++++++++++++---- 1 file changed, 91 insertions(+), 10 deletions(-) diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 81412e6..9b544fa 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -32,13 +32,15 @@ fn vendor_pubkey_pem() -> &'static str { /// Engine versions this build ships, gating `engine_min_version`. Mirrors /// `fixtures/modelpack/context.json` (`whisper.cpp`, `sherpa-onnx`). NOTE: /// derive these from the bundled engine crates later rather than hard-coding. +/// +/// No `llama.cpp` yet: this build doesn't link it, so a signed LLM pack is +/// listed as "engine not supported by this build" rather than as verified. +/// Add `"llama.cpp" => "0.6.0"` (the version `llama-cpp-sys-2 =0.1.161` +/// vendors, spike S5) when P2 links it. fn engine_versions() -> BTreeMap { let mut m = BTreeMap::new(); m.insert("whisper.cpp".to_string(), "1.7.0".to_string()); m.insert("sherpa-onnx".to_string(), "2.0.1".to_string()); - // llama.cpp v0.6.0 (commit d812350), as vendored by llama-cpp-sys-2 =0.1.161 - // (spike S5). No llama.cpp is linked into the app yet. - m.insert("llama.cpp".to_string(), "0.6.0".to_string()); m } @@ -298,17 +300,31 @@ fn manifest_sha256(dir: &Path) -> Result { .ok_or_else(|| format!("manifest in {} has no sha256", dir.display())) } -/// Verify every pack directory in `packs_dir`, returning the verified ones. +/// The `task` a pack's manifest declares, read WITHOUT verifying it. Used only to +/// skip packs a resolver could never use before hashing their weights (a +/// multi-GB LLM pack takes seconds); every pack a resolver keeps is still fully +/// verified, so a forged `task` can only make a pack be skipped. +fn declared_task(dir: &Path) -> Option { + let bytes = std::fs::read(dir.join("manifest.json")).ok()?; + let value: Value = serde_json::from_slice(&bytes).ok()?; + value.get("task").and_then(Value::as_str).map(str::to_string) +} + +/// Verify every pack directory in `packs_dir` whose declared task passes +/// `wanted`, returning the verified ones. Packs with an unreadable manifest are +/// still verified (and so rejected). fn verified_packs( packs_dir: &Path, pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, + wanted: impl Fn(&str) -> bool, ) -> Vec<(PathBuf, PackStatus)> { let mut out: Vec<(PathBuf, PackStatus)> = match std::fs::read_dir(packs_dir) { Ok(entries) => entries .filter_map(|e| e.ok()) .map(|e| e.path()) .filter(|p| p.is_dir()) + .filter(|p| declared_task(p).is_none_or(|t| wanted(&t))) .map(|p| { let status = verify_pack_dir(&p, pubkey, engine_versions); (p, status) @@ -339,11 +355,12 @@ pub fn resolve_verified_models_dir_in( asr_model: engine::AsrModel, diarize: bool, ) -> Result { - let verified_dirs: Vec = verified_packs(packs_dir, pubkey, engine_versions) - .into_iter() - .filter(|(_, status)| status.task != LLM_TASK) - .map(|(dir, _)| dir) - .collect(); + let verified_dirs: Vec = + verified_packs(packs_dir, pubkey, engine_versions, |task| task != LLM_TASK) + .into_iter() + .filter(|(_, status)| status.task != LLM_TASK) + .map(|(dir, _)| dir) + .collect(); if verified_dirs.is_empty() { return Err(format!( "no verified model pack found in {}", @@ -426,7 +443,7 @@ pub fn resolve_verified_llm_in( engine_versions: &BTreeMap, ) -> Result { let mut llm_packs: Vec<(PathBuf, PackStatus)> = - verified_packs(packs_dir, pubkey, engine_versions) + verified_packs(packs_dir, pubkey, engine_versions, |task| task == LLM_TASK) .into_iter() .filter(|(_, status)| status.task == LLM_TASK) .collect(); @@ -785,4 +802,68 @@ mod tests { let _ = fs::remove_dir_all(&packs); let _ = fs::remove_dir_all(&cache_base); } + + /// Resolving speech models never reads an LLM pack's weights (a multi-GB + /// hash would hold up every recording start). The LLM pack's `weights.bin` + /// here is a FIFO with no writer, so opening it blocks: the resolve only + /// returns if it never touches that file. + #[cfg(unix)] + #[test] + fn resolving_speech_models_never_reads_an_llm_packs_weights() { + let (pem, versions) = fixtures_context(); + let packs = unique_tmp("speech-skips-llm-packs"); + copy_fixture_pack("asr-small-en", &packs); + let llm = packs.join("llm-tiny"); + fs::create_dir_all(&llm).unwrap(); + fs::copy( + repo_root().join("fixtures/modelpack/packs/llm-tiny/manifest.json"), + llm.join("manifest.json"), + ) + .unwrap(); + let mkfifo = std::process::Command::new("mkfifo") + .arg(llm.join("weights.bin")) + .status() + .unwrap(); + assert!(mkfifo.success()); + let cache_base = unique_tmp("speech-skips-llm-cache"); + + let (tx, rx) = std::sync::mpsc::channel(); + let (p, c) = (packs.clone(), cache_base.clone()); + std::thread::spawn(move || { + let pubkey = PublicKey::SpkiPem(&pem); + let r = resolve_verified_models_dir_in( + &p, + &c, + &pubkey, + &versions, + engine::AsrModel::SmallEn, + false, + ); + let _ = tx.send(r); + }); + let resolved = rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("speech resolve blocked opening the LLM pack's weights"); + + assert!(resolved.is_ok(), "got: {resolved:?}"); + let _ = fs::remove_dir_all(&packs); + let _ = fs::remove_dir_all(&cache_base); + } + + /// This build links no llama.cpp, so a correctly signed LLM pack is + /// reported as not usable rather than as verified. + #[test] + fn this_build_does_not_verify_llm_packs() { + let (pem, _) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let pack = repo_root().join("fixtures/modelpack/packs/llm-tiny"); + + let status = verify_pack_dir(&pack, &pubkey, &engine_versions()); + + assert!(!status.verified); + assert_eq!( + status.reason.as_deref(), + Some("engine not supported by this build (no \"llama.cpp\" engine available)") + ); + } } From d47acd21c4b4224f119b1c7ef1889775e3c76d60 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 09:51:28 +0000 Subject: [PATCH 08/10] modelpack-sign: stage and self-verify before replacing a pack; refuse an out-dir inside the model dir Streaming into weights.bin (S5) truncated an existing pack before the source was read, so a failed rebuild left a broken pack, and an out-dir inside the model dir zipped its own partial output. The pack is now built as .weights.bin.partial / .manifest.json.partial, self-verified, then renamed into place; an out-dir inside the model dir is refused up front. --- tools/modelpack-sign/src/lib.rs | 80 ++++++++++++++++++++--- tools/modelpack-sign/tests/pack_output.rs | 71 ++++++++++++++++++++ 2 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 tools/modelpack-sign/tests/pack_output.rs diff --git a/tools/modelpack-sign/src/lib.rs b/tools/modelpack-sign/src/lib.rs index 0c4ca47..aa782ec 100644 --- a/tools/modelpack-sign/src/lib.rs +++ b/tools/modelpack-sign/src/lib.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; @@ -296,10 +296,33 @@ pub fn build_manifest_json(meta: &PackMeta, sha256: &str, signature: &str) -> se }) } -/// Full `pack` pipeline: zip the model dir straight into `weights.bin`, hash it -/// in chunks, sign, write the manifest, then self-verify (again streaming) with -/// the real `modelpack` verifier before returning. Nothing is held in memory -/// whole, so multi-GB LLM packs sign in flat memory. +/// `path` with symlinks and `..` resolved, even when its last components don't +/// exist yet: the nearest existing ancestor is canonicalized and the rest appended. +fn resolved(path: &Path) -> Result { + let abs = std::path::absolute(path) + .with_context(|| format!("resolving {}", path.display()))?; + let mut rest = Vec::new(); + let mut base = abs.as_path(); + while !base.exists() { + rest.push(base.file_name().unwrap_or_default().to_owned()); + base = base + .parent() + .with_context(|| format!("no existing ancestor of {}", abs.display()))?; + } + let mut out = base + .canonicalize() + .with_context(|| format!("resolving {}", base.display()))?; + out.extend(rest.iter().rev()); + Ok(out) +} + +/// Full `pack` pipeline: zip the model dir into a staging file in `out_dir`, +/// hash it in chunks, sign, write a staged manifest, and self-verify (again +/// streaming) with the real `modelpack` verifier. Only then are the staged +/// files renamed over `weights.bin` and `manifest.json`, so a failed rebuild +/// leaves an existing pack as it was. Nothing is held in memory whole, so +/// multi-GB LLM packs sign in flat memory. `out_dir` must not be inside +/// `model_dir`, or the pack would zip its own output. pub fn pack( model_dir: &Path, out_dir: &Path, @@ -309,19 +332,56 @@ pub fn pack( let signing = SigningKey::from_pkcs8_pem(private_pem).context("loading signing key from PKCS8 PEM")?; + if !model_dir.is_dir() { + bail!("model dir {} is not a directory", model_dir.display()); + } + if resolved(out_dir)?.starts_with(resolved(model_dir)?) { + bail!( + "pack out-dir {} is inside the model dir {}; choose an out-dir outside it", + out_dir.display(), + model_dir.display() + ); + } + std::fs::create_dir_all(out_dir) .with_context(|| format!("creating pack out-dir {}", out_dir.display()))?; + let staged_weights = out_dir.join(".weights.bin.partial"); + let staged_manifest = out_dir.join(".manifest.json.partial"); + let built = build_staged(model_dir, &staged_weights, &staged_manifest, &signing, meta); + if built.is_err() { + let _ = std::fs::remove_file(&staged_weights); + let _ = std::fs::remove_file(&staged_manifest); + return built; + } + + // The weights go first: if the second rename fails, the old manifest no + // longer matches and the pack is rejected, never wrongly accepted. let weights_path = out_dir.join("weights.bin"); let manifest_path = out_dir.join("manifest.json"); - zip_model_dir_to(model_dir, &weights_path)?; - let sha256 = modelpack::sha256_hex_file(&weights_path) + std::fs::rename(&staged_weights, &weights_path) + .with_context(|| format!("replacing {}", weights_path.display()))?; + std::fs::rename(&staged_manifest, &manifest_path) + .with_context(|| format!("replacing {}", manifest_path.display()))?; + Ok(()) +} + +/// Zip, hash, sign and self-verify into the two staging paths. +fn build_staged( + model_dir: &Path, + weights_path: &Path, + manifest_path: &Path, + signing: &SigningKey, + meta: &PackMeta, +) -> Result<()> { + zip_model_dir_to(model_dir, weights_path)?; + let sha256 = modelpack::sha256_hex_file(weights_path) .with_context(|| format!("hashing {}", weights_path.display()))?; - let signature = sign_manifest(&signing, meta, &sha256); + let signature = sign_manifest(signing, meta, &sha256); let manifest_json = build_manifest_json(meta, &sha256, &signature); let manifest_pretty = serde_json::to_string_pretty(&manifest_json).context("serializing manifest json")?; - std::fs::write(&manifest_path, manifest_pretty.as_bytes()) + std::fs::write(manifest_path, manifest_pretty.as_bytes()) .with_context(|| format!("writing {}", manifest_path.display()))?; // Self-verify with the real verifier, using the public key derived from the @@ -331,7 +391,7 @@ pub fn pack( .to_public_key_pem(LineEnding::LF) .context("deriving public SPKI PEM for self-check")?; let engine_versions = self_check_engine_versions(); - let weights = std::fs::File::open(&weights_path) + let weights = std::fs::File::open(weights_path) .with_context(|| format!("opening {}", weights_path.display()))?; modelpack::verify_model_pack_reader( &manifest_json, diff --git a/tools/modelpack-sign/tests/pack_output.rs b/tools/modelpack-sign/tests/pack_output.rs new file mode 100644 index 0000000..f65291b --- /dev/null +++ b/tools/modelpack-sign/tests/pack_output.rs @@ -0,0 +1,71 @@ +//! Where `pack` writes, and what it leaves behind when it fails. + +use std::path::{Path, PathBuf}; + +use modelpack_sign::{generate_keypair, pack, verify_pack, PackMeta}; + +fn unique_tmp(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "mps-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} + +fn meta() -> PackMeta { + PackMeta { + id: "test/tiny".to_string(), + version: "1.0.0".to_string(), + engine: "sherpa-onnx".to_string(), + engine_min_version: "1.0.0".to_string(), + task: "asr".to_string(), + license: "MIT".to_string(), + attribution: "Test".to_string(), + } +} + +fn model_dir(root: &Path) -> PathBuf { + let model = root.join("model"); + std::fs::create_dir_all(&model).unwrap(); + std::fs::write(model.join("tokens.txt"), b"a 0\nb 1\n").unwrap(); + model +} + +#[test] +fn a_pack_inside_its_own_model_dir_is_refused() { + let tmp = unique_tmp("out-inside"); + let model = model_dir(&tmp); + let out = model.join("pack"); + let (private_pem, _) = generate_keypair().unwrap(); + + let result = pack(&model, &out, &private_pem, &meta()); + + assert!(result.is_err(), "packing into the model dir must be refused"); + assert!(!out.join("weights.bin").exists()); + let _ = std::fs::remove_dir_all(&tmp); +} + +#[cfg(unix)] +#[test] +fn a_failed_repack_leaves_the_existing_pack_intact() { + use std::os::unix::fs::PermissionsExt; + + let tmp = unique_tmp("failed-repack"); + let model = model_dir(&tmp); + let out = tmp.join("pack"); + let (private_pem, public_pem) = generate_keypair().unwrap(); + pack(&model, &out, &private_pem, &meta()).unwrap(); + let unreadable = model.join("z-unreadable.onnx"); + std::fs::write(&unreadable, b"weights").unwrap(); + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).unwrap(); + + let repack = pack(&model, &out, &private_pem, &meta()); + + std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert!(repack.is_err(), "a source file that can't be read must fail the pack"); + assert!(verify_pack(&out, &public_pem).is_ok(), "the earlier pack must still verify"); + let _ = std::fs::remove_dir_all(&tmp); +} From 060764e3a984e2b9e429878c4a3e78d827008b3c Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 09:53:05 +0000 Subject: [PATCH 09/10] spike(s5): keep the VAD session open through generation; commit prompt.py; reject --threads < 1 - --vad dropped its sherpa-onnx session before llama.cpp loaded, so the two runtimes never held sessions at once. The session now stays open and runs again after generation. - The documented benchmark used an uncommitted prompt.py; it is committed (byte-identical output: the 730-token housing-visit prompt). - ggml silently replaces --threads 0 with 4, mislabelling runs. --- spikes/s5-llama/prompt.py | 12 ++++++++++ spikes/s5-llama/src/main.rs | 46 +++++++++++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 10 deletions(-) create mode 100644 spikes/s5-llama/prompt.py diff --git a/spikes/s5-llama/prompt.py b/spikes/s5-llama/prompt.py new file mode 100644 index 0000000..49fd5be --- /dev/null +++ b/spikes/s5-llama/prompt.py @@ -0,0 +1,12 @@ +"""Print the synthetic prompt S5's generation timings used (730 tokens with Qwen3's chat template): +24 lines of a housing-visit transcript and an instruction to list its facts.""" +lines = [] +names = ["Sam", "Priya"] +facts = ["the boiler was serviced in March", "the tenant reported damp in the back bedroom", + "rent is paid on the first of the month", "the landlord agreed to inspect the window seals", + "a follow-up visit is booked for next Thursday", "the tenant has two children under five", + "the council letter arrived on the twelfth", "the deposit is held in a protection scheme"] +for i in range(24): + lines.append(f"[{i*15//60:02d}:{i*15%60:02d}] {names[i%2]}: I can confirm that {facts[i%len(facts)]}, " + "and we discussed what happens next.") +print("Write a short note of the key facts from this transcript excerpt, as bullet points.\n\n" + "\n".join(lines)) diff --git a/spikes/s5-llama/src/main.rs b/spikes/s5-llama/src/main.rs index 044bc26..23e5c70 100644 --- a/spikes/s5-llama/src/main.rs +++ b/spikes/s5-llama/src/main.rs @@ -5,13 +5,15 @@ //! Usage: //! s5-llama --self-check //! Starts sherpa-onnx/onnxruntime and the llama.cpp CPU backend, then exits -//! 0. No model needed (this is what CI runs on Windows, macOS and Linux). +//! 0. No model needed (this is what CI runs on Windows, macOS and Linux). A +//! link-and-backend smoke test: it opens no inference session. //! s5-llama --model [--threads 4] [--n-predict 64] [--ctx 2048] //! [--prompt "..."] [--vad ] //! Loads the GGUF on the CPU and generates up to `--n-predict` tokens, //! printing load time, prompt and generation tokens/s, and peak RSS. -//! `--vad` also runs a Silero VAD session through sherpa-onnx in the same -//! process first, so both runtimes have live threads and allocations. +//! `--vad` also opens a Silero VAD session through sherpa-onnx first and +//! keeps it open through generation, running it again afterwards, so both +//! runtimes hold live sessions and allocations at the same time. //! //! Throwaway spike code: not linked into the app. @@ -48,7 +50,13 @@ fn parse_args() -> Result { "--self-check" => a.self_check = true, "--model" => a.model = Some(PathBuf::from(value()?)), "--vad" => a.vad = Some(PathBuf::from(value()?)), - "--threads" => a.threads = value()?.parse().map_err(|e| format!("--threads: {e}"))?, + "--threads" => { + a.threads = value()?.parse().map_err(|e| format!("--threads: {e}"))?; + // ggml silently swaps a value below 1 for its default (4). + if a.threads < 1 { + return Err("--threads must be at least 1".into()); + } + } "--n-predict" => { a.n_predict = value()?.parse().map_err(|e| format!("--n-predict: {e}"))? } @@ -116,8 +124,9 @@ fn sherpa_check() -> Result<(), String> { Ok(()) } -/// Run a real Silero VAD session through sherpa-onnx on one second of silence. -fn sherpa_vad(path: &std::path::Path) -> Result<(), String> { +/// Open a real Silero VAD session through sherpa-onnx and run it on one second +/// of silence. The session is returned so the caller can keep it open. +fn sherpa_vad(path: &std::path::Path) -> Result { let t = Instant::now(); let mut silero = sherpa_onnx::SileroVadModelConfig::default(); silero.model = Some(path.to_string_lossy().into_owned()); @@ -144,7 +153,19 @@ fn sherpa_vad(path: &std::path::Path) -> Result<(), String> { t.elapsed().as_secs_f64() * 1e3, !vad.is_empty() ); - Ok(()) + Ok(vad) +} + +/// Run the still-open VAD session again, after llama.cpp has generated. +fn sherpa_vad_again(vad: &sherpa_onnx::VoiceActivityDetector) { + let t = Instant::now(); + vad.reset(); + vad.accept_waveform(&vec![0.0f32; 16_000]); + vad.flush(); + println!( + "sherpa VAD: same session ran 1 s of silence again after generation in {:.0} ms", + t.elapsed().as_secs_f64() * 1e3 + ); } #[cfg(feature = "llama")] @@ -278,9 +299,11 @@ mod llama { fn run() -> Result<(), String> { let a = parse_args()?; sherpa_check()?; - if let Some(vad) = &a.vad { - sherpa_vad(vad)?; - } + // Kept open until the end of `run`, so it is live while llama.cpp loads and generates. + let vad = match &a.vad { + Some(path) => Some(sherpa_vad(path)?), + None => None, + }; #[cfg(feature = "llama")] { @@ -294,6 +317,9 @@ fn run() -> Result<(), String> { if a.model.is_some() { return Err("built without the `llama` feature; rebuild with default features".into()); } + if let Some(vad) = &vad { + sherpa_vad_again(vad); + } println!( "OK: self-check passed; peak RSS {:.0} MB", From 4a22b18ed8a9396988c62cb0bbb4f97757c95978 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Wed, 25 Nov 2026 09:53:47 +0000 Subject: [PATCH 10/10] docs(s5): review fixes: llm/llama.cpp pairing, staged signing, LLM packs unsupported in this build, VAD kept open (runs 7-9), CI status --- docs/model-packs.md | 21 ++++++---- docs/spikes/next-phase-spikes.md | 2 +- docs/spikes/s5-llm-packaging.md | 68 ++++++++++++++++++++------------ 3 files changed, 57 insertions(+), 34 deletions(-) diff --git a/docs/model-packs.md b/docs/model-packs.md index 5420363..2c54be3 100644 --- a/docs/model-packs.md +++ b/docs/model-packs.md @@ -18,8 +18,9 @@ A pack is a directory of two files: `task`, `license`, `attribution`, `sha256`, and `signature`. `task` is one of `asr`, `diarization` or `llm`; `engine` is one of `sherpa-onnx`, -`whisper.cpp` or `llama.cpp`. Packs are hashed and extracted as streams, so a -multi-GB pack never has to fit in memory. +`whisper.cpp` or `llama.cpp`. `llm` and `llama.cpp` go together: an `llm` pack on +another engine, or another task on `llama.cpp`, is rejected. Packs are hashed and +extracted as streams, so a multi-GB pack never has to fit in memory. ### Language-model packs (`task: "llm"`) @@ -27,16 +28,18 @@ An LLM pack carries one GGUF file for the `llama.cpp` engine. The signer stores `.gguf` files in the zip **uncompressed** (they are already quantised; Deflate would cost minutes of CPU for almost nothing), and everything else Deflated as before. The app resolves an LLM pack separately from speech packs: speech -resolution never extracts an LLM pack, and `resolve_verified_llm` +resolution skips LLM packs without hashing them, and `resolve_verified_llm` (`app/src-tauri/src/models.rs`) returns the GGUF path only from a verified `task: "llm"` pack, failing closed otherwise. Nothing in the app calls it yet; it is groundwork for local notes (P2), measured in spike S5 ([`spikes/s5-llm-packaging.md`](spikes/s5-llm-packaging.md)). The `llama.cpp` engine version is llama.cpp's own release version (it uses semver -since v0.6.0). This build records **0.6.0**: the llama.cpp commit `d812350` that -`llama-cpp-sys-2 =0.1.161` vendors. An LLM pack should set -`--engine-min-version 0.6.0` until a newer llama.cpp is linked. +since v0.6.0). The signer and the conformance fixtures record **0.6.0**: the +llama.cpp commit `d812350` that `llama-cpp-sys-2 =0.1.161` vendors. An LLM pack +should set `--engine-min-version 0.6.0` until a newer llama.cpp is linked. The app +links no llama.cpp yet, so its engine map leaves it out and it lists an imported +LLM pack as "engine not supported by this build" until P2 adds it. ## How verification works @@ -132,8 +135,10 @@ cargo run --release --manifest-path tools/modelpack-sign/Cargo.toml -- pack \ --attribution "Qwen3-4B-Instruct-2507 by the Qwen Team, Alibaba Cloud (Apache-2.0)" ``` -The `pack` command self-verifies after writing, so a pack that's produced is guaranteed -to pass the in-app verifier (with the matching key). To check an existing pack: +The `pack` command builds the pack in staging files and self-verifies it before +replacing `weights.bin` and `manifest.json`, so a pack that's produced is guaranteed +to pass the in-app verifier (with the matching key), and a failed rebuild leaves the +previous pack as it was. `--out` must be outside `--model-dir`. To check an existing pack: ```bash cargo run --manifest-path tools/modelpack-sign/Cargo.toml -- verify \ diff --git a/docs/spikes/next-phase-spikes.md b/docs/spikes/next-phase-spikes.md index 7b10904..34e2754 100644 --- a/docs/spikes/next-phase-spikes.md +++ b/docs/spikes/next-phase-spikes.md @@ -137,7 +137,7 @@ hard gate for social-care templates.** ## S5: Packaging, licensing and zero-egress -> **Result: go, with conditions** (Mac; Windows cross-linked only; the new CI job still to run): see [`s5-llm-packaging.md`](s5-llm-packaging.md). Harness: `spikes/s5-llama/`. +> **Result: go, with conditions** (measured on a Mac; CI green on Linux with no network, macOS and Windows, where the binary links and starts both runtimes without a model; no model loaded on Windows yet): see [`s5-llm-packaging.md`](s5-llm-packaging.md). Harness: `spikes/s5-llama/`. **Question.** Can llama.cpp be linked in-process, built from vendored sources, and shipped with its weights as a signed model pack, without adding a network crate or a licence we can't redistribute? diff --git a/docs/spikes/s5-llm-packaging.md b/docs/spikes/s5-llm-packaging.md index 1f642e4..9993fca 100644 --- a/docs/spikes/s5-llm-packaging.md +++ b/docs/spikes/s5-llm-packaging.md @@ -1,7 +1,7 @@ # Spike S5: packaging, licensing and zero-egress for the local LLM > Status: **GO-WITH-CONDITIONS** (Mac measured; CI green on Linux with no network, macOS and Windows, where the -> binary runs a self-check without a model) · Recorded 2026-11-24. +> binary links and starts both runtimes without a model) · Recorded 2026-11-24, review fixes 2026-11-25. > Plan: [`next-phase-spikes.md`](next-phase-spikes.md#s5-packaging-licensing-and-zero-egress). > Harness: `spikes/s5-llama/` (one binary linking llama.cpp and the engine's sherpa-onnx). @@ -20,7 +20,7 @@ fails closed after a one-byte change; and both candidate weights are plain Apach |---|---|---| | Gate green | `scripts/check-no-network.sh` passes, now also scanning `spikes/s5-llama` on all targets | **Pass** | | Reproducible static build, no build-time download | Mac: clean build with outbound network denied by the OS sandbox; two clean builds gave bit-identical binaries. Linux (CI): builds inside a network namespace with no network. Windows (CI, real MSVC): links once condition 2's CMake setting is in, and the self-check runs | **Pass** | -| Signed pack verifies and loads | `task: "llm"` pack signed, verified by the app's resolver, GGUF loaded and generating; one flipped byte rejected | **Pass** | +| Signed pack verifies and loads | `task: "llm"` pack signed, verified by the app's LLM resolver (given an engine map with llama.cpp, as P2's build will have), GGUF loaded and generating; one flipped byte rejected | **Pass** | | Weights licence cleared | Qwen3-4B-Instruct-2507 and Qwen3.5-4B: Apache-2.0, ungated, no use policy, no NOTICE | **Pass** | **Conditions:** @@ -44,15 +44,17 @@ fails closed after a one-byte change; and both candidate weights are plain Apach 3. **Keep the `s5-llama` CI job (or its equivalent for the app) green.** On its first run it caught condition 2 on real MSVC, which the cross-build had hidden. It now passes on all three: the Linux leg builds inside a network namespace with no network (the CI-side proof of "no build-time download"), and on Windows the binary - runs its self-check (sherpa-onnx 2.0.1 / onnxruntime 1.28.2 plus the llama.cpp backend in one process). No - model has been loaded on Windows yet; that is for the reference laptop. + runs its self-check (sherpa-onnx 2.0.1 / onnxruntime 1.28.2 plus the llama.cpp backend in one process). The + self-check is a link-and-backend smoke test: it opens no inference session in either runtime. No model has + been loaded on Windows yet; that is for the reference laptop. 4. **Validate llama.cpp inputs before calling it.** llama.cpp **aborts the process** on misuse instead of returning an error: the first long-prompt run here died on `GGML_ASSERT(n_tokens_all <= cparams.n_batch)`. Inside the app that kills the whole app, so P2's wrapper must check prompt length against `n_batch`/`n_ctx` (or run the LLM in a child process). 5. **Decide the LLM pack layout for P2.** The spike keeps the existing pack format (a zip in `weights.bin`, with the GGUF Stored). That costs a second 2.4 GB copy on disk (pack plus extracted GGUF) and the - extracted copy is trusted from the cache without being re-hashed (the speech packs work the same way). Since + extracted copy is trusted from the cache without being re-hashed, and the resolver re-opens the pack by path + after verifying it rather than extracting the bytes it hashed (the speech packs work the same way). Since a Stored zip gains nothing for one file, consider letting an `llm` pack's `weights.bin` *be* the GGUF: verify it, then load it in place. @@ -70,7 +72,8 @@ fails closed after a one-byte change; and both candidate weights are plain Apach `sherpa-onnx =2.0.1` (onnxruntime 1.28.2), the same version the engine pins. - **Build settings** (`spikes/s5-llama/.cargo/config.toml`): `GGML_METAL=OFF` (CPU only; llama-cpp-2 turns on the sys crate's `metal` feature on Apple Silicon, so only the Metal framework link remains), - `CMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `LLAMA_STATIC_CRT=1`. `GGML_OPENMP` is off (no OpenMP runtime to + `CMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `LLAMA_STATIC_CRT=1`, `CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded` + (condition 2). `GGML_OPENMP` is off (no OpenMP runtime to clash with onnxruntime's threads), `GGML_NATIVE` off, `LLAMA_CURL` off. - **Weights:** `Qwen3-4B-Instruct-2507-Q4_0.gguf` (2,375,773,280 bytes, SHA-256 `e0ba675d…13be2`, matching the Hugging Face LFS hash of `unsloth/Qwen3-4B-Instruct-2507-GGUF`) and `Qwen3.5-4B-Q4_0.gguf` (`298fcb5f…b72b8bb`, @@ -92,8 +95,8 @@ sandbox-exec -p '(version 1)(allow default)(deny network-outbound (remote ip))' cargo build --offline --release --no-default-features --target-dir target-nollama ./target-sandbox/release/s5-llama --self-check -/usr/bin/time -l ./target-sandbox/release/s5-llama --model Qwen3-4B-Instruct-2507-Q4_0.gguf \ - --threads 4 --n-predict 64 --prompt "$(python3 prompt.py)" --vad silero_vad.onnx +P="$(python3 prompt.py)" && /usr/bin/time -l ./target-sandbox/release/s5-llama \ + --model Qwen3-4B-Instruct-2507-Q4_0.gguf --threads 4 --n-predict 64 --prompt "$P" --vad silero_vad.onnx # Windows cross-check (scripts/build-windows-on-mac.sh has the one-time setup): cargo xwin build --release --target x86_64-pc-windows-msvc --target-dir target-xwin @@ -107,7 +110,7 @@ modelpack-sign pack --model-dir /tmp/s5/model --out /tmp/s5/packs/llm-qwen3-4b-i modelpack-sign verify --pack /tmp/s5/packs/llm-qwen3-4b-instruct-2507 --pubkey /tmp/s5/keys/public.spki.pem ``` -`prompt.py` printed a 24-line synthetic housing-visit transcript with an instruction to list its facts (730 +`prompt.py` (in the harness) prints a 24-line synthetic housing-visit transcript with an instruction to list its facts (730 tokens with Qwen3's chat template). The app-side resolve was measured with a temporary, uncommitted `#[ignore]` test calling `resolve_verified_llm_in` on the real pack, run under `/usr/bin/time -l`. "Before" numbers come from `main`'s `tools/modelpack-sign`, built from `git archive main`. @@ -154,9 +157,10 @@ without llama.cpp, 22,466,048 B with it (**+4.4 MB, +24%**). The `.exe` imports ### Both runtimes in one process `--self-check` prints sherpa-onnx 2.0.1 / onnxruntime 1.28.2, runs `SherpaEngine::new` (fails closed with no -models, as it should), starts the llama.cpp backend (devices: `CPU` only) and exits 0, at 10 MB peak RSS. -`--vad` also runs a real Silero VAD session through sherpa-onnx (52 ms for 1 s of audio) before llama.cpp -loads. No duplicate symbols, no thread-pool clash. +models, as it should), starts the llama.cpp backend (devices: `CPU` only) and exits 0, at 10 MB peak RSS. It +opens no inference session, so it proves linking and backend start-up, not two live runtimes. +`--vad` opens a real Silero VAD session through sherpa-onnx (11–52 ms for 1 s of audio) and keeps it open while +llama.cpp loads and generates, then runs it again (2 ms). No duplicate symbols, no thread-pool clash. ### Generation, Qwen3-4B-Instruct-2507 Q4_0, 4 threads, CPU, 2k context, greedy @@ -168,8 +172,13 @@ loads. No duplicate symbols, no thread-pool clash. | 4 | 16 | 1.48 s | 101.8 tok/s | 34.0 tok/s | 2.77 GB | 5.14 GB | | 5 | 16 | 0.80 s | 99.2 tok/s | 27.9 tok/s | 2.77 GB | 5.14 GB | | 6 | 16 | 0.96 s | 92.0 tok/s | 28.1 tok/s | 2.76 GB | 5.14 GB | +| 7 | 16 | 1.86 s | 114.4 tok/s | 34.7 tok/s | 2.77 GB | 5.10 GB | +| 8 | 17 | 0.67 s | 116.4 tok/s | 36.7 tok/s | 2.77 GB | 5.14 GB | +| 9 | 16 | 0.61 s | 116.3 tok/s | 36.8 tok/s | 2.77 GB | 5.14 GB | -Every run also ran the Silero VAD session through sherpa-onnx first. Qwen3.5-4B Q4_0, same prompt (754 tokens) at load 16: load +Every run also ran a Silero VAD session through sherpa-onnx. In runs 1–6 that session was closed before +llama.cpp loaded; runs 7–9 (2026-11-25, after the review) kept it open through generation, with the same +footprint. Qwen3.5-4B Q4_0, same prompt (754 tokens) at load 16: load 2.03 s, prompt 81.5 tok/s, generation 26.0 tok/s, footprint 2.83 GB. Load times are with the GGUF in the page cache. "Peak footprint" is macOS's physical footprint; RSS also counts the memory-mapped GGUF pages and so overstates real use (S2 saw the same). The loaded-machine figures match S2's medians (prefill 53, generation 16 @@ -193,7 +202,8 @@ resolver returned `no verified LLM model pack found` and `modelpack-sign verify` hash mismatch (tampered or corrupt)`. Disk use per installed LLM is about 4.75 GB: the 2.38 GB pack plus the 2.38 GB extracted GGUF (condition 5). -Re-verifying the pack costs about 6 s of hashing each time it is resolved. +Re-verifying the pack costs about 6 s of hashing each time it is resolved. Speech resolution, which runs at every +recording start, skips LLM packs before hashing them. ## Licences @@ -211,20 +221,28 @@ but shouldn't brand anything as Qwen. The rows are in `docs/assurance/third-part ## Pack support added on this branch -- `modelpack` (Rust) and `core/src/modelpack.ts` accept `task: "llm"` and `engine: "llama.cpp"`. The - conformance fixtures gained a `valid-llm` case; `context.json` gives `llama.cpp` version 0.6.0. +- `modelpack` (Rust) and `core/src/modelpack.ts` accept `task: "llm"` and `engine: "llama.cpp"`, only together: + an `llm` pack on another engine, or another task on `llama.cpp`, is rejected. The conformance fixtures gained + `valid-llm` and `malformed-llm-wrong-engine` cases; `context.json` gives `llama.cpp` version 0.6.0. - `modelpack` hashes weights from a stream in 1 MiB chunks (`verify_model_pack_reader`, `sha256_hex_file`); `verify_model_pack` over a byte slice still works as before. -- `modelpack-sign` has `--task llm`, zips straight into `weights.bin` (each file streamed in; `.gguf` Stored, +- `modelpack-sign` has `--task llm`, zips into a staging file (each file streamed in; `.gguf` Stored, everything else Deflated as before; zip64 for files of 4 GiB or more), hashes and self-verifies by streaming, - and knows `llama.cpp` 0.6.0. -- The app (`app/src-tauri/src/models.rs`) verifies and extracts packs by streaming, keeps LLM packs out of the - speech-model cache, and has `resolve_verified_llm_in` / `resolve_verified_llm`, which return the GGUF path - from the newest verified `llm` pack and fail closed otherwise. Nothing calls them yet. + and only then replaces `weights.bin` and `manifest.json`, so a failed rebuild leaves the old pack intact. It + refuses an out-dir inside the model dir, and knows `llama.cpp` 0.6.0. +- The app (`app/src-tauri/src/models.rs`) verifies and extracts packs by streaming, skips LLM packs before + hashing them when resolving speech models, and has `resolve_verified_llm_in` / `resolve_verified_llm`, which + return the GGUF path from the newest verified `llm` pack and fail closed otherwise. Nothing calls them yet. + The app's own engine map leaves `llama.cpp` out until P2 links it, so this build lists a signed LLM pack as + "engine not supported by this build" and `resolve_verified_llm` fails closed; `resolve_verified_llm_in` takes + the engine map as an argument, which is how it was measured. - Tests (the agreed list): the `valid-llm` and unknown-task conformance cases (Rust and TS); `--task llm` through the real CLI producing a pack the verifier accepts; the app resolving a signed LLM fixture pack to its GGUF, rejecting a tampered one, and never returning a speech pack as an LLM; and a streamed hash of a - file larger than one chunk against a `shasum`-computed literal. + file larger than one chunk against a `shasum`-computed literal. The Codex review on 2026-11-25 added one + regression test per bug it found: `malformed-llm-wrong-engine`, speech resolution never opening an LLM + pack's weights, this build not verifying LLM packs, a failed repack leaving the old pack intact, and an + out-dir inside the model dir being refused. ## What changes in the PRD @@ -232,7 +250,8 @@ but shouldn't brand anything as Qwen. The rows are in `docs/assurance/third-part `GGML_METAL=OFF`, `LLAMA_STATIC_CRT=1`, OpenMP off, and the `common` fix from condition 1. JSON-schema to grammar conversion (`json_schema_to_grammar`) needs `common`; for P3 prefer GBNF grammars given directly to `LlamaSampler::grammar`, which works without it. -- **Delivery:** the pack manifest gains `task: "llm"` and `engine: "llama.cpp"` (done here), and resolution +- **Delivery:** the pack manifest gains `task: "llm"` and `engine: "llama.cpp"`, only as a pair (done here); P2 + adds `llama.cpp` to the app's engine map when it links it; and resolution uses `resolve_verified_llm`, not `resolve_verified_models_dir`, which now ignores LLM packs. Decide the pack layout (condition 5). - **Sizes:** the app binary grows by about 4 MB; the LLM pack is about 2.4 GB to download and 4.75 GB on disk @@ -243,8 +262,7 @@ but shouldn't brand anything as Qwen. The rows are in `docs/assurance/third-part ## Still to do -- Run the `s5-llama` CI job on all three platforms, including the no-network Linux build, and run the - Windows binary (only cross-linked here). +- Load a model and generate on Windows (CI's self-check opens no inference session). - Repeat the generation timings on the reference Windows laptop, ideally with the app's live ASR running. - Build a release installer with llama.cpp linked to measure its size (only the binary was measured). - The signer's self-check still knows sherpa-onnx as 1.13.2 while the app ships 2.0.1, so it would refuse a