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/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 236da22..9b544fa 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}; @@ -33,6 +32,11 @@ 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()); @@ -40,6 +44,9 @@ fn engine_versions() -> BTreeMap { 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 +80,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 +107,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 +239,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 +272,77 @@ 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())) +} + +/// 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) + }) + .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 +355,12 @@ 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, |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 {}", @@ -304,16 +370,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 +387,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 +427,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, |task| task == LLM_TASK) + .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 +735,135 @@ 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); + } + + /// 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)") + ); + } } diff --git a/core/src/modelpack.ts b/core/src/modelpack.ts index bb4d3ed..fdfa20e 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]; /** @@ -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/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..2c54be3 100644 --- a/docs/model-packs.md +++ b/docs/model-packs.md @@ -17,6 +17,30 @@ 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`. `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"`) + +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 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). 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 When you import a pack (or at transcription time), the verifier checks, in order, and @@ -63,6 +87,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,8 +124,21 @@ 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 -to pass the in-app verifier (with the matching key). To check an existing pack: +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 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 fef707d..34e2754 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** (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 new file mode 100644 index 0000000..9993fca --- /dev/null +++ b/docs/spikes/s5-llm-packaging.md @@ -0,0 +1,269 @@ +# 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 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). + +## 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. 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 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:** +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.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. **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). 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, 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. + +## 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`, `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`, + 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 +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 + +# 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` (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`. + +## 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. 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 + +| 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 | +| 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 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 +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. Speech resolution, which runs at every +recording start, skips LLM packs before hashing them. + +## 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"`, 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 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 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. 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 + +- **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"`, 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 + 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 + +- 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 + pack with `--engine-min-version 2.0.1`. This predates S5 and is left as it was. diff --git a/fixtures/modelpack/README.md b/fixtures/modelpack/README.md index 76fbba5..4f6dfe8 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 | @@ -63,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/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 0000000..b7c580c Binary files /dev/null and b/fixtures/modelpack/cases/valid-llm/weights.bin differ 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 0000000..7d1db8b Binary files /dev/null and b/fixtures/modelpack/packs/llm-tiny/weights.bin differ diff --git a/modelpack/src/lib.rs b/modelpack/src/lib.rs index 49f45cb..8cd6547 100644 --- a/modelpack/src/lib.rs +++ b/modelpack/src/lib.rs @@ -27,6 +27,8 @@ use std::cmp::Ordering; use std::collections::BTreeMap; +use std::io::Read; +use std::path::Path; use base64::Engine as _; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; @@ -37,10 +39,14 @@ use serde_json::Value; use sha2::{Digest, Sha256}; /// Engines this build knows how to drive (mirrors `ENGINES` in the TS). -pub const ENGINES: [&str; 2] = ["whisper.cpp", "sherpa-onnx"]; +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; 2] = ["asr", "diarization"]; +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 @@ -193,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) { @@ -256,12 +269,51 @@ pub fn verify_model_pack( weights: &[u8], pubkey: &PublicKey<'_>, 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 +427,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/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/scripts/gen-modelpack-fixtures.ts b/scripts/gen-modelpack-fixtures.ts index a0ad9a4..aff3386 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); @@ -258,4 +275,14 @@ function baseManifest(overrides: Record = {}): Record [--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 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. + +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}"))?; + // 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}"))? + } + "--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(()) +} + +/// 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()); + 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(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")] +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()?; + // 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")] + { + 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()); + } + if let Some(vad) = &vad { + sherpa_vad_again(vad); + } + + 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); + } +} 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..aa782ec 100644 --- a/tools/modelpack-sign/src/lib.rs +++ b/tools/modelpack-sign/src/lib.rs @@ -7,8 +7,8 @@ //! and verifies. use std::collections::BTreeMap; -use std::io::{Cursor, Read, Write}; -use std::path::Path; +use std::io::Write; +use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; @@ -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,33 @@ 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. +/// `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, @@ -289,20 +332,56 @@ 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); + 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"); - std::fs::write(&weights_path, &zip_bytes) - .with_context(|| format!("writing {}", weights_path.display()))?; + 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 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 @@ -312,9 +391,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 +404,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); +} 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); +}