Format the control-plane, engine-host and library crates at 120 columns (rustfmt.toml) and drop stale docs/ references

This commit is contained in:
Pavlo Ratushnyi
2026-11-23 09:34:30 +01:00
parent deae0aa6ba
commit 8b34c9506e
741 changed files with 7977 additions and 22040 deletions
+1 -1
View File
@@ -19,4 +19,4 @@ cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-respons
cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- --sse benchmarks/fixtures/responses/structured-tool.json
```
See [API contract](../docs/api-contract.md) for the supported subset and remaining integration work.
See API contract (spec node `api-contract.md`) for the supported subset and remaining integration work.
+6 -23
View File
@@ -26,11 +26,8 @@ fn main() {
type BuildResult<T> = Result<T, Box<dyn std::error::Error>>;
/// The three variables that configure an embedded engine: all unset, or all set.
const ENGINE_VARS: [&str; 3] = [
"STRATA_EMBED_ENGINE_PATH",
"STRATA_EMBED_ENGINE_SHA256",
"STRATA_EMBED_ENGINE_REVISION",
];
const ENGINE_VARS: [&str; 3] =
["STRATA_EMBED_ENGINE_PATH", "STRATA_EMBED_ENGINE_SHA256", "STRATA_EMBED_ENGINE_REVISION"];
fn embed_engine() -> BuildResult<()> {
use std::{env, fs, path::PathBuf};
@@ -70,16 +67,8 @@ fn write_payload(
return Ok((String::new(), String::new()));
}
let file = open_engine(values)?;
let digest = values[1]
.as_ref()
.unwrap()
.to_str()
.ok_or("digest must be ASCII")?;
let revision = values[2]
.as_ref()
.unwrap()
.to_str()
.ok_or("revision must be ASCII")?;
let digest = values[1].as_ref().unwrap().to_str().ok_or("digest must be ASCII")?;
let revision = values[2].as_ref().unwrap().to_str().ok_or("revision must be ASCII")?;
embedded_spec::copy_verified(
file,
fs::File::create(payload_path)?,
@@ -141,11 +130,7 @@ fn engine_assembly(path: &str) -> String {
}
/// Assembles the payload into the crate and returns the Rust declaration of `BYTES` for it.
fn payload_declaration(
output: &std::path::Path,
payload_path: &std::path::Path,
size: u64,
) -> BuildResult<String> {
fn payload_declaration(output: &std::path::Path, payload_path: &std::path::Path, size: u64) -> BuildResult<String> {
// Keep large verified payloads out of Rust constant evaluation/LLVM IR.
// The target assembler copies the bytes into an immutable ELF section.
let path = payload_path.to_str().ok_or("payload path must be UTF-8")?;
@@ -155,9 +140,7 @@ fn payload_declaration(
let path = path.replace('\\', "\\\\").replace('"', "\\\"");
let assembly = output.join("embedded-engine.S");
std::fs::write(&assembly, engine_assembly(&path))?;
cc::Build::new()
.file(assembly)
.compile("strata_embedded_payload");
cc::Build::new().file(assembly).compile("strata_embedded_payload");
Ok(format!(
"unsafe extern \"C\" {{ static strata_embedded_engine_bytes: [u8; {size}]; }}\n\
// SAFETY: build.rs emits exactly {size} verified bytes in read-only storage.\n\
+2 -10
View File
@@ -33,11 +33,7 @@ fn compare_blocks(source: &mut File, blocks: u64) -> Result<(), Failure> {
source.read_exact(&mut block)?;
let rust = iq3_s::decode_block(&block)?;
ggml_bridge::decode_into(21, &block, &mut ggml)?;
if let Some(position) = rust
.iter()
.zip(&ggml)
.position(|(left, right)| left.to_bits() != right.to_bits())
{
if let Some(position) = rust.iter().zip(&ggml).position(|(left, right)| left.to_bits() != right.to_bits()) {
return Err(format!(
"block {number}, value {position}: Rust={:#010x}, ggml={:#010x}",
rust[position].to_bits(),
@@ -53,11 +49,7 @@ fn main() -> Result<(), Failure> {
let (path, requested) = parse_args()?;
let path = Path::new(&path);
let index = gguf::tensor_index(path)?;
let tensor = index
.tensors
.iter()
.find(|tensor| tensor.kind == 21)
.ok_or("GGUF has no IQ3_S tensor")?;
let tensor = index.tensors.iter().find(|tensor| tensor.kind == 21).ok_or("GGUF has no IQ3_S tensor")?;
let blocks = requested.min(tensor.bytes / iq3_s::BLOCK_BYTES as u64);
let mut source = File::open(path)?;
source.seek(SeekFrom::Start(index.summary.data_start + tensor.offset))?;
+2 -12
View File
@@ -45,13 +45,7 @@ fn parse_args() -> Result<Args, Failure> {
if args.next().is_some() || count == 0 || count > 1_000_000 {
return Err(USAGE.into());
}
Ok(Args {
source_path,
archive_path,
level,
start,
count,
})
Ok(Args { source_path, archive_path, level, start, count })
}
/// `(elements, bytes)` of one block of the supported source kinds.
@@ -94,11 +88,7 @@ impl ErrorSums {
}
fn relative_l2(&self) -> f64 {
if self.reference == 0.0 {
self.error.sqrt()
} else {
(self.error / self.reference).sqrt()
}
if self.reference == 0.0 { self.error.sqrt() } else { (self.error / self.reference).sqrt() }
}
}
+18 -66
View File
@@ -13,9 +13,7 @@ pub(super) static MAX_OUTPUT: AtomicU64 = AtomicU64::new(0);
pub(super) static STORE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(super) fn unix_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis())
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis())
}
pub(super) fn number_after(text: &[u8], key: &[u8]) -> u64 {
@@ -31,39 +29,22 @@ pub(super) fn number_after(text: &[u8], key: &[u8]) -> u64 {
pub(super) fn find(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
let start = from.saturating_sub(needle.len());
haystack[start.min(haystack.len())..]
.windows(needle.len())
.position(|w| w == needle)
.map(|p| p + start)
haystack[start.min(haystack.len())..].windows(needle.len()).position(|w| w == needle).map(|p| p + start)
}
const FIRST_DELTA_EVENTS: [&[u8]; 3] = [
b"response.reasoning_text.delta",
b"response.output_text.delta",
b"response.function_call_arguments.delta",
];
const FIRST_DELTA_EVENTS: [&[u8]; 3] =
[b"response.reasoning_text.delta", b"response.output_text.delta", b"response.function_call_arguments.delta"];
const TERMINAL_EVENTS: [&str; 3] = [
"response.completed",
"response.incomplete",
"response.failed",
];
const TERMINAL_EVENTS: [&str; 3] = ["response.completed", "response.incomplete", "response.failed"];
/// The first terminal event name found in the body (empty when there is none).
fn terminal_event(text: &[u8]) -> String {
TERMINAL_EVENTS
.into_iter()
.find(|name| find(text, 0, name.as_bytes()).is_some())
.unwrap_or("")
.to_owned()
TERMINAL_EVENTS.into_iter().find(|name| find(text, 0, name.as_bytes()).is_some()).unwrap_or("").to_owned()
}
/// `input_tokens` / `cached_tokens` of the terminal event's usage.
fn usage_of(tail: &[u8]) -> (u64, u64) {
(
number_after(tail, b"\"input_tokens\":"),
number_after(tail, b"\"cached_tokens\":"),
)
(number_after(tail, b"\"input_tokens\":"), number_after(tail, b"\"cached_tokens\":"))
}
/// What has arrived of one response so far, with the instants the replay measures.
@@ -120,16 +101,10 @@ impl ReplyScan {
};
self.header_end = Some(end + 4);
let head = String::from_utf8_lossy(&self.data[..end]).to_ascii_lowercase();
self.status = head
.split_whitespace()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
self.status = head.split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0);
self.chunked = head.contains("transfer-encoding: chunked");
self.content_length = head
.lines()
.find_map(|l| l.strip_prefix("content-length: "))
.and_then(|v| v.trim().parse::<usize>().ok());
self.content_length =
head.lines().find_map(|l| l.strip_prefix("content-length: ")).and_then(|v| v.trim().parse::<usize>().ok());
true
}
@@ -137,10 +112,7 @@ impl ReplyScan {
fn mark_events(&mut self, before: usize, start: usize) {
if self.t_first_delta == 0 {
let from = self.scanned.max(start).min(before.max(start));
if FIRST_DELTA_EVENTS
.iter()
.any(|name| find(&self.data, from, name).is_some())
{
if FIRST_DELTA_EVENTS.iter().any(|name| find(&self.data, from, name).is_some()) {
self.t_first_delta = now_ns();
}
}
@@ -148,10 +120,7 @@ impl ReplyScan {
if self.t_created == 0 && find(&self.data, from, b"response.created").is_some() {
self.t_created = now_ns();
}
if self.t_completed == 0
&& TERMINAL_EVENTS
.iter()
.any(|name| find(&self.data, from, name.as_bytes()).is_some())
if self.t_completed == 0 && TERMINAL_EVENTS.iter().any(|name| find(&self.data, from, name.as_bytes()).is_some())
{
self.t_completed = now_ns();
}
@@ -188,8 +157,7 @@ impl ReplyScan {
t_first_delta: self.t_first_delta,
t_completed: self.t_completed,
saw_function_call: find(text, 0, b"\"type\":\"function_call\"").is_some(),
saw_completed: terminal == "response.completed"
|| find(text, 0, b"\"status\":\"completed\"").is_some(),
saw_completed: terminal == "response.completed" || find(text, 0, b"\"status\":\"completed\"").is_some(),
sent_unix_ms: self.sent_unix_ms,
done_unix_ms: unix_ms(),
usage: usage_of(tail),
@@ -199,19 +167,12 @@ impl ReplyScan {
}
async fn send_request(conn: &mut TcpStream, path: &str, body: &[u8], stream: bool) {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let auth = AUTH.get().map(|value| format!("Authorization: Bearer {value}\r\n")).unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\n\
Content-Length: {}\r\nAccept: {}\r\n{auth}\r\n",
body.len(),
if stream {
"text/event-stream"
} else {
"application/json"
}
if stream { "text/event-stream" } else { "application/json" }
);
conn.write_all(head.as_bytes()).await.unwrap();
conn.write_all(body).await.unwrap();
@@ -263,12 +224,7 @@ pub(super) fn load_session(path: &str) -> Session {
instructions: doc["instructions"].as_str().unwrap().to_owned(),
tools: doc["tools"].as_array().unwrap().clone(),
items: doc["items"].as_array().unwrap().clone(),
rounds: doc["rounds"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_u64().unwrap() as usize)
.collect(),
rounds: doc["rounds"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap() as usize).collect(),
capture_items: doc["capture_items"].as_u64().unwrap_or(0) as usize,
capture_ids: doc["capture_prompt_ids"]
.as_array()
@@ -309,16 +265,12 @@ pub(super) async fn token_count(conn: &mut TcpStream, session: &Session, round:
let bytes = serde_json::to_vec(&body).unwrap();
// reuse the sender, response is small JSON
let reply = request_raw(conn, "/v1/responses/input_tokens", &bytes).await;
let value: Value =
serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
let value: Value = serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
value["input_tokens"].as_u64().unwrap() as usize
}
pub(super) async fn request_raw(conn: &mut TcpStream, path: &str, body: &[u8]) -> String {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let auth = AUTH.get().map(|value| format!("Authorization: Bearer {value}\r\n")).unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{auth}\r\n",
body.len()
@@ -19,8 +19,7 @@ pub struct EngineMarks {
pub last_prompt: Mutex<Option<String>>,
}
pub(super) static KEEP_PROMPT: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub(super) static KEEP_PROMPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// How long the instant engine waits after taking the prompt before its first token (a real engine needs far longer;
/// the wait lets the response's opening events leave first, as they do in production).
@@ -55,12 +54,8 @@ pub(super) fn reply_text() -> String {
/// Stamps the arrival of the prompt and records its size, hash and (for `--verify`) text.
fn record_request(marks: &EngineMarks, request: &GenerationRequest) {
marks.received.store(now_ns(), Ordering::SeqCst);
marks
.prompt_bytes
.store(request.prompt.len() as u64, Ordering::SeqCst);
marks
.prompt_hash
.store(fnv(request.prompt.as_bytes()), Ordering::SeqCst);
marks.prompt_bytes.store(request.prompt.len() as u64, Ordering::SeqCst);
marks.prompt_hash.store(fnv(request.prompt.as_bytes()), Ordering::SeqCst);
if KEEP_PROMPT.load(Ordering::Relaxed) {
*marks.last_prompt.lock().unwrap() = Some(request.prompt.clone());
}
@@ -78,21 +73,14 @@ fn spawn_reply(reply: Vec<String>, marks: Arc<EngineMarks>, sink: GenerationSink
} else if gap > 0 {
std::thread::sleep(Duration::from_micros(gap));
}
if sink
.emit(GenerationEvent::TextDelta { text: piece })
.is_err()
{
if sink.emit(GenerationEvent::TextDelta { text: piece }).is_err() {
return;
}
}
marks.terminal.store(now_ns(), Ordering::SeqCst);
let _ = sink.complete(
FinishReason::Stop,
Usage {
input_tokens: input,
output_tokens: 420,
reused_input_tokens: input * 97 / 100,
},
Usage { input_tokens: input, output_tokens: 420, reused_input_tokens: input * 97 / 100 },
);
});
}
+7 -25
View File
@@ -4,20 +4,11 @@ use super::*;
/// The key (read from a file, never printed), the model name and the output cap of the `--live` requests.
fn set_live_credentials(args: &[String]) {
let key = std::fs::read_to_string(arg(args, "--key-file").expect("--key-file"))
.expect("key file")
.trim()
.to_owned();
let key =
std::fs::read_to_string(arg(args, "--key-file").expect("--key-file")).expect("key file").trim().to_owned();
AUTH.set(key).ok();
MODEL
.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into()))
.ok();
MAX_OUTPUT.store(
arg(args, "--max-output-tokens")
.and_then(|v| v.parse().ok())
.unwrap_or(48),
Ordering::Relaxed,
);
MODEL.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into())).ok();
MAX_OUTPUT.store(arg(args, "--max-output-tokens").and_then(|v| v.parse().ok()).unwrap_or(48), Ordering::Relaxed);
}
async fn connect_all(urls: &[String]) -> Vec<TcpStream> {
@@ -32,18 +23,11 @@ async fn connect_all(urls: &[String]) -> Vec<TcpStream> {
}
/// `--first-round R`, or the round whose prompt is closest to `--size N` tokens.
async fn first_live_round(
conn: &mut TcpStream,
session: &Session,
args: &[String],
turns: usize,
) -> usize {
async fn first_live_round(conn: &mut TcpStream, session: &Session, args: &[String], turns: usize) -> usize {
match arg(args, "--first-round").and_then(|v| v.parse::<usize>().ok()) {
Some(round) => round,
None => {
let size: usize = arg(args, "--size")
.and_then(|v| v.parse().ok())
.unwrap_or(60000);
let size: usize = arg(args, "--size").and_then(|v| v.parse().ok()).unwrap_or(60000);
closest_round(conn, session, size, turns).await
}
}
@@ -76,9 +60,7 @@ pub(super) async fn live(targets: &str, session: Session, args: &[String]) {
let names: Vec<String> = arg(args, "--names")
.map(|v| v.split(',').map(str::to_owned).collect())
.unwrap_or_else(|| (0..urls.len()).map(|i| format!("arm{i}")).collect());
let turns: usize = arg(args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let turns: usize = arg(args, "--turns").and_then(|v| v.parse().ok()).unwrap_or(24);
let mut conns = connect_all(&urls).await;
let first = first_live_round(&mut conns[0], &session, args, turns).await;
let first = first.min(session.rounds.len().saturating_sub(turns));
+17 -59
View File
@@ -1,4 +1,4 @@
//! Host-side latency replay (`docs/cp-latency.md`): Codex-shaped Responses requests with a growing history sent over
//! Host-side latency replay: Codex-shaped Responses requests with a growing history sent over
//! real loopback HTTP to the real router, the real worker adapter and the real tokenizer, in front of an *instant*
//! engine that returns a canned reply the moment it has the prompt. Everything this prints is therefore the cost of the
//! control plane outside the engine, per stage; it says nothing about the engine.
@@ -34,6 +34,7 @@ use live::*;
mod verify;
use verify::*;
use leleka_control_plane::app::{EngineLink, ModelView};
use std::{
collections::BTreeMap,
io::Write as _,
@@ -44,14 +45,11 @@ use std::{
},
time::{Duration, Instant},
};
use leleka_control_plane::app::{EngineLink, ModelView};
use leleka_backend_api::{
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
GenerationRequest, GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig,
SupportedModelTuple, Usage,
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent, GenerationRequest,
GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig, SupportedModelTuple, Usage,
};
use serde_json::{Value, json};
use leleka_control_plane::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker},
@@ -59,6 +57,7 @@ use leleka_control_plane::{
tokenizer::Tokenizer,
worker::{WorkerState, WorkerStatus},
};
use serde_json::{Value, json};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
@@ -66,18 +65,13 @@ use tokio::{
};
fn arg(args: &[String], name: &str) -> Option<String> {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1).cloned())
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
#[allow(dead_code)]
#[tokio::main]
async fn main() {
run(std::env::args().collect(), async |marks| {
Box::new(InstantBackend::new(marks)) as Box<dyn Backend>
})
.await;
run(std::env::args().collect(), async |marks| Box::new(InstantBackend::new(marks)) as Box<dyn Backend>).await;
}
/// The command-line choices of the plain replay.
@@ -94,17 +88,10 @@ fn replay_plan(args: &[String]) -> ReplayPlan {
.split(',')
.map(|s| s.parse().unwrap())
.collect();
let turns: usize = arg(args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let turns: usize = arg(args, "--turns").and_then(|v| v.parse().ok()).unwrap_or(24);
let stream = !args.iter().any(|a| a == "--json-response");
let label = arg(args, "--label").unwrap_or_else(|| "run".into());
ReplayPlan {
sizes,
turns,
stream,
label,
}
ReplayPlan { sizes, turns, stream, label }
}
/// `--store`, `--engine-delay-ms` and `--delta-gap-us` reach the client and the instant engine through statics.
@@ -121,9 +108,7 @@ fn set_load_flags(args: &[String]) {
}
fn exit_with_usage() -> ! {
eprintln!(
"usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]"
);
eprintln!("usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]");
std::process::exit(2);
}
@@ -172,13 +157,7 @@ async fn connect(addr: std::net::SocketAddr) -> TcpStream {
}
/// Replays one history size: finds its round, then measures `turns` consecutive rounds on a fresh stack.
async fn replay_size<F>(
tokenizer_dir: &Path,
session: &Session,
make: &F,
plan: &ReplayPlan,
size: usize,
) -> Value
async fn replay_size<F>(tokenizer_dir: &Path, session: &Session, make: &F, plan: &ReplayPlan, size: usize) -> Value
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
@@ -198,12 +177,7 @@ where
}
/// Picks the round whose prompt is closest to `size` tokens (counted by the server itself).
async fn closest_round(
conn: &mut TcpStream,
session: &Session,
size: usize,
turns: usize,
) -> usize {
async fn closest_round(conn: &mut TcpStream, session: &Session, size: usize, turns: usize) -> usize {
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
while low < high {
let mid = (low + high) / 2;
@@ -232,10 +206,7 @@ async fn replay_turns(
let body = body_at(session, round, plan.stream);
let reply = request(conn, "/v1/responses", &body, plan.stream).await;
assert_eq!(reply.status, 200, "turn {turn}");
assert!(
reply.saw_completed && reply.saw_function_call,
"turn {turn}: incomplete reply"
);
assert!(reply.saw_completed && reply.saw_function_call, "turn {turn}: incomplete reply");
rows.push(turn_row((turn, round), body.len(), &stack.marks, &reply));
}
rows
@@ -250,12 +221,7 @@ fn stages_json() -> serde_json::Map<String, Value> {
stage_json
}
fn turn_row(
(turn, round): (usize, usize),
body_len: usize,
marks: &EngineMarks,
reply: &Reply,
) -> Value {
fn turn_row((turn, round): (usize, usize), body_len: usize, marks: &EngineMarks, reply: &Reply) -> Value {
let received = marks.received.load(Ordering::SeqCst);
let first_delta = marks.first_delta.load(Ordering::SeqCst);
let terminal = marks.terminal.load(Ordering::SeqCst);
@@ -290,10 +256,7 @@ fn print_summary(label: &str, size: usize, first: usize, rows: &[Value]) {
rows[0]["prompt_bytes"].as_f64().unwrap() / 1024.0,
warm.len()
);
println!(
"{:<22} {:>9} {:>9} {:>9}",
"metric (ms)", "cold", "p50", "p95"
);
println!("{:<22} {:>9} {:>9} {:>9}", "metric (ms)", "cold", "p50", "p95");
for key in ["pre_engine_ms", "first_event_ms", "tail_ms", "wall_ms"] {
println!(
"{:<22} {:>9.2} {:>9.2} {:>9.2}",
@@ -310,19 +273,14 @@ fn print_stage_rows(cold: &Value, warm: &[&Value]) {
let mut stage_names: BTreeMap<String, Vec<f64>> = BTreeMap::new();
for row in warm {
for (name, value) in row["stages"].as_object().unwrap() {
stage_names
.entry(name.clone())
.or_default()
.push(value["ms"].as_f64().unwrap());
stage_names.entry(name.clone()).or_default().push(value["ms"].as_f64().unwrap());
}
}
for (name, values) in &stage_names {
println!(
" stage {:<18} {:>9.2} {:>9.2} {:>9.2}",
name,
cold["stages"]
.get(name)
.map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
cold["stages"].get(name).map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
percentile(values, 0.5),
percentile(values, 0.95)
);
+3 -14
View File
@@ -47,9 +47,7 @@ fn app_state(
},
model: ModelView {
name: Some("fixture".into()),
tokenizer: Some(Arc::new(leleka_control_plane::codec::qwen_codec_shared(
tokenizer.clone(),
))),
tokenizer: Some(Arc::new(leleka_control_plane::codec::qwen_codec_shared(tokenizer.clone()))),
..Default::default()
},
..Default::default()
@@ -101,10 +99,7 @@ fn spawn_worker(
config,
status,
stop_rx,
WorkerInbox {
requests: requests_rx,
control: control_rx,
},
WorkerInbox { requests: requests_rx, control: control_rx },
));
(stop, requests, control, worker)
}
@@ -122,13 +117,7 @@ where
let state = app_state(&status, requests, control, &tokenizer);
let (addr, server) = serve(router(state)).await;
await_ready(&status).await;
Stack {
addr,
marks,
stop,
worker,
server,
}
Stack { addr, marks, stop, worker, server }
}
impl Stack {
+5 -20
View File
@@ -6,19 +6,9 @@ use super::*;
fn check_prompt_ids(reference: &Tokenizer, round: usize, prompt: &str, counted: usize) -> Vec<u32> {
let fast = reference.encode(prompt, true).unwrap();
let slow = reference.encode_reference(prompt, true).unwrap();
assert_eq!(
fast, slow,
"round {round}: fast path ids differ from the reference"
);
assert_eq!(
fast.len(),
counted,
"round {round}: input_tokens differs from the ids"
);
assert!(
reference.decodes_to(&fast, prompt.as_bytes()),
"round {round}: ids do not decode to the prompt"
);
assert_eq!(fast, slow, "round {round}: fast path ids differ from the reference");
assert_eq!(fast.len(), counted, "round {round}: input_tokens differs from the ids");
assert!(reference.decodes_to(&fast, prompt.as_bytes()), "round {round}: ids do not decode to the prompt");
fast
}
@@ -84,10 +74,7 @@ async fn verify_round(
return false;
}
check_capture(reference, session, round, &fast);
println!(
"CAPTURE round={round} tokens={} identical to the captured prompt ids",
fast.len()
);
println!("CAPTURE round={round} tokens={} identical to the captured prompt ids", fast.len());
true
}
@@ -103,9 +90,7 @@ where
{
KEEP_PROMPT.store(true, Ordering::Relaxed);
let reference = Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets");
let step: usize = arg(args, "--verify-step")
.and_then(|v| v.parse().ok())
.unwrap_or(1);
let step: usize = arg(args, "--verify-step").and_then(|v| v.parse().ok()).unwrap_or(1);
let stack = start_stack(tokenizer_dir, make).await;
let mut conn = connect(stack.addr).await;
let mut checked = 0;
+6 -26
View File
@@ -1,30 +1,19 @@
//! Model-free routed-expert fixture, using the production KAR writer.
use leleka_control_plane::kar_writer::{self, SourceIdentity, Tensor, TensorData};
use sha2::{Digest, Sha256};
use std::path::Path;
use leleka_control_plane::kar_writer::{self, SourceIdentity, Tensor, TensorData};
const H: u64 = 64;
const F: u64 = 32;
const E: u64 = 2;
const ROLE_BYTES: usize = (H * F * E * 4) as usize;
const NAMES: [&str; 3] = [
"blk.0.ffn_gate_exps.weight",
"blk.0.ffn_up_exps.weight",
"blk.0.ffn_down_exps.weight",
];
const NAMES: [&str; 3] = ["blk.0.ffn_gate_exps.weight", "blk.0.ffn_up_exps.weight", "blk.0.ffn_down_exps.weight"];
/// The three raw F32 tensors: expert 0 is 1/32 everywhere and expert 1 is -1/32.
fn raw_source() -> Vec<u8> {
(0..3)
.flat_map(|_| {
(0..H * F * E).flat_map(|i| {
(if i < H * F {
1.0f32 / 32.0
} else {
-1.0f32 / 32.0
})
.to_le_bytes()
})
(0..H * F * E).flat_map(|i| (if i < H * F { 1.0f32 / 32.0 } else { -1.0f32 / 32.0 }).to_le_bytes())
})
.collect()
}
@@ -54,15 +43,7 @@ fn expert_tensor<'a>(
source_dtype: 0,
source_digest: Sha256::digest(&raw[role * ROLE_BYTES..(role + 1) * ROLE_BYTES]).into(),
source_offset: (role * ROLE_BYTES) as u64,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 1,
scales,
books,
planes,
},
data: TensorData::Nested { group: 32, nesting: 0, planes_min: 1, planes_max: 1, scales, books, planes },
}
}
@@ -80,9 +61,8 @@ fn main() -> Result<(), String> {
let raw = raw_source();
let source = source_identity(&raw);
let dims = [[H, F, E], [H, F, E], [F, H, E]];
let tensors: Vec<_> = (0..3)
.map(|role| expert_tensor(role, &raw, &dims[role], (&scales, &books, &planes)))
.collect();
let tensors: Vec<_> =
(0..3).map(|role| expert_tensor(role, &raw, &dims[role], (&scales, &books, &planes))).collect();
kar_writer::write_archive(Path::new(&args[1]), &source, &tensors)?;
Ok(())
}
+5 -17
View File
@@ -3,30 +3,20 @@
use std::{collections::BTreeMap, env, fs::File, path::Path};
use sha2::{Digest, Sha256};
use leleka_control_plane::{gguf, gguf_f32_stream};
use sha2::{Digest, Sha256};
type Failure = Box<dyn std::error::Error>;
fn all_finite(values: &[u8]) -> bool {
values
.as_chunks::<4>()
.0
.iter()
.all(|word| f32::from_le_bytes(*word).is_finite())
values.as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_finite())
}
/// Decodes the first block of `tensor` and prints its element count and the SHA-256 of the decoded values.
fn scan_kind(
source: &mut File,
data_start: u64,
(kind, tensor): (u32, &gguf::TensorInfo),
) -> Result<(), Failure> {
fn scan_kind(source: &mut File, data_start: u64, (kind, tensor): (u32, &gguf::TensorInfo)) -> Result<(), Failure> {
let (expected_elements, bytes) =
gguf::block_geometry(kind).ok_or_else(|| format!("unsupported source kind {kind}"))?;
let absolute = data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
let absolute = data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?;
let mut hasher = Sha256::new();
let decoded_bytes = gguf_f32_stream::visit(source, absolute, kind, bytes, |_, values| {
if !all_finite(values) {
@@ -48,9 +38,7 @@ fn scan_kind(
}
fn main() -> Result<(), Failure> {
let path = env::args()
.nth(1)
.ok_or("usage: scan-quant-blocks FILE.gguf")?;
let path = env::args().nth(1).ok_or("usage: scan-quant-blocks FILE.gguf")?;
let path = Path::new(&path);
let index = gguf::tensor_index(path)?;
let mut first_by_kind = BTreeMap::new();
+3
View File
@@ -0,0 +1,3 @@
# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line.
max_width = 120
use_small_heuristics = "Max"
+3 -15
View File
@@ -22,10 +22,7 @@ impl ChannelEngine {
}
/// A command channel of `capacity` places and its engine; the worker side reads the receiver.
pub fn channel(
capacity: usize,
clock: SharedClock,
) -> (SharedEngine, mpsc::Receiver<GenerationCommand>) {
pub fn channel(capacity: usize, clock: SharedClock) -> (SharedEngine, mpsc::Receiver<GenerationCommand>) {
let (sender, receiver) = mpsc::channel(capacity);
(Arc::new(Self::new(sender, clock)), receiver)
}
@@ -37,17 +34,8 @@ impl ChannelEngine {
}
impl EngineClient for ChannelEngine {
fn submit(
&self,
command: GenerationCommand,
budget: Option<Duration>,
) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(queue::enqueue_with(
&self.sender,
command,
budget,
self.clock.clone(),
))
fn submit(&self, command: GenerationCommand, budget: Option<Duration>) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(queue::enqueue_with(&self.sender, command, budget, self.clock.clone()))
}
fn queue_capacity(&self) -> usize {
+2 -8
View File
@@ -8,10 +8,7 @@ use crate::{
};
impl VisionEncoder for Vision {
fn encode_all<'a>(
&'a self,
sources: &'a [String],
) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>> {
fn encode_all<'a>(&'a self, sources: &'a [String]) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>> {
Box::pin(async move {
// Encode only while the engine is idle: the gate is also taken for every engine generation.
let _turn = self.gate.lock().await;
@@ -23,10 +20,7 @@ impl VisionEncoder for Vision {
})
}
fn combine<'a>(
&'a self,
images: &'a [Encoded],
) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> {
fn combine<'a>(&'a self, images: &'a [Encoded]) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> {
Box::pin(Vision::combine(self, images))
}
}
+4 -15
View File
@@ -16,10 +16,7 @@ pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serd
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
&& matches!(worker.state, WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded);
Json(
serde_json::json!({"service":"leleka-control-plane", "server_pid":std::process::id(), "model":state.model.name,
"draining":lifecycle.draining,
@@ -75,17 +72,9 @@ pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) ->
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept`
/// that asks for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept
/// generation, not the last 12.
pub(super) async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQuery, headers: HeaderMap) -> Response {
let accept = headers.get(axum::http::header::ACCEPT).and_then(|v| v.to_str().ok());
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
+11 -35
View File
@@ -23,9 +23,7 @@ impl Gathered {
let memory = state.model.memory.status();
let (hardware, hardware_static, telemetry, history) = state.model.memory.hardware();
let busy = generation.active_since.is_some();
let elapsed_ms = generation
.active_since
.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
let elapsed_ms = generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
Self {
worker,
busy,
@@ -41,22 +39,14 @@ impl Gathered {
/// The value while a request is running, `null` otherwise.
fn while_busy(&self, value: &serde_json::Value) -> serde_json::Value {
if self.busy {
value.clone()
} else {
serde_json::Value::Null
}
if self.busy { value.clone() } else { serde_json::Value::Null }
}
fn engine_state(&self, phase: Option<&str>) -> serde_json::Value {
if self.worker.state != WorkerState::Ready {
serde_json::to_value(self.worker.state).unwrap_or(serde_json::Value::Null)
} else if self.busy {
serde_json::json!(if phase == Some("prefill") {
"reading"
} else {
"generating"
})
serde_json::json!(if phase == Some("prefill") { "reading" } else { "generating" })
} else {
serde_json::json!("idle")
}
@@ -92,16 +82,8 @@ impl Gathered {
/// Identity, queue and memory gate of the process.
fn process_block(&self, state: &AppState) -> serde_json::Value {
let queue_capacity = state
.engine
.client
.as_ref()
.map(|engine| engine.queue_capacity());
let queue_used = state
.engine
.client
.as_ref()
.map(|engine| engine.queue_used());
let queue_capacity = state.engine.client.as_ref().map(|engine| engine.queue_capacity());
let queue_used = state.engine.client.as_ref().map(|engine| engine.queue_used());
serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
@@ -122,8 +104,7 @@ impl Gathered {
fn generation_block(&self, state: &AppState) -> serde_json::Value {
let generation = self.worker.metrics;
let decode_rate =
crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms);
let decode_rate = crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms);
serde_json::json!({
"generation": generation,
"done_decode_tokens_per_second": decode_rate,
@@ -134,11 +115,9 @@ impl Gathered {
fn requests_block(&self, state: &AppState, all_requests: bool) -> serde_json::Value {
let (requests, requests_kept, totals) = match self.worker.metrics.history {
Some(history) => (
history.requests((!all_requests).then_some(RECENT_REQUESTS)),
history.kept(),
history.totals(),
),
Some(history) => {
(history.requests((!all_requests).then_some(RECENT_REQUESTS)), history.kept(), history.totals())
}
None => (Vec::new(), 0, serde_json::Value::Null),
};
serde_json::json!({
@@ -182,8 +161,7 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso
/// Seconds since the API started, on the state's clock.
pub(crate) fn uptime_s(state: &AppState) -> u64 {
let now = state.services.clock.system_time();
now.duration_since(state.services.started_at)
.map_or(0, |d| d.as_secs())
now.duration_since(state.services.started_at).map_or(0, |d| d.as_secs())
}
/// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service.
@@ -198,9 +176,7 @@ pub(super) fn supervisor_block() -> serde_json::Value {
let Ok(status) = serde_json::from_str::<serde_json::Value>(&text) else {
return serde_json::Value::Null;
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
serde_json::json!({
"phase": status["phase"],
"restarts_total": status["restarts_total"],
+3 -14
View File
@@ -9,15 +9,8 @@ pub(super) async fn ready(State(state): State<AppState>) -> (StatusCode, Json<St
&& state.model.tokenizer.is_some()
&& state.engine.client.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model.name)),
)
let code = if inference_ready { StatusCode::OK } else { StatusCode::SERVICE_UNAVAILABLE };
(code, Json(status_body(worker, inference_ready, state.model.name)))
}
pub(super) async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
@@ -40,11 +33,7 @@ pub(super) async fn pool_ready(state: &AppState) -> bool {
true
}
pub(super) fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
pub(super) fn status_body(worker: WorkerStatus, inference_ready: bool, model: Option<String>) -> StatusResponse {
StatusResponse {
service: "leleka-control-plane",
server_pid: std::process::id(),
+15 -53
View File
@@ -10,10 +10,7 @@ type Routes = Router<AppState>;
/// The handler behind the admission gate of the lifecycle (drain and the in-flight limit).
fn admitted(state: &AppState, handler: MethodRouter<AppState>) -> MethodRouter<AppState> {
handler.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
handler.layer(middleware::from_fn_with_state(state.lifecycle.clone(), crate::lifecycle::admit))
}
/// The handler with its request captured for the monitor and recorded in the request log.
@@ -23,14 +20,8 @@ fn recorded(
handler: MethodRouter<AppState>,
) -> MethodRouter<AppState> {
handler
.layer(middleware::from_fn_with_state(
state.services.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
))
.layer(middleware::from_fn_with_state(state.services.monitor.clone(), crate::request_monitor::capture))
.layer(middleware::from_fn_with_state(observe.clone(), crate::request_log::observe))
}
/// Health, status, metrics, the llama.cpp style endpoints, settings and model loading.
@@ -47,10 +38,7 @@ fn server_routes(router: Routes) -> Routes {
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/settings", get(crate::server_api::settings_get).post(crate::server_api::settings_post))
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
@@ -64,18 +52,11 @@ fn model_routes(router: Routes) -> Routes {
.route("/v1/models/{id}", get(crate::models_api::retrieve))
}
fn response_routes(
router: Routes,
state: &AppState,
observe: &crate::request_log::Observe,
) -> Routes {
fn response_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
let create = admitted(state, post(responses::create_route));
router
.route("/v1/responses", recorded(state, observe, create))
.route(
"/v1/responses/input_tokens",
admitted(state, post(responses::count_input_tokens)),
)
.route("/v1/responses/input_tokens", admitted(state, post(responses::count_input_tokens)))
}
fn chat_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
@@ -83,18 +64,11 @@ fn chat_routes(router: Routes, state: &AppState, observe: &crate::request_log::O
router.route("/v1/chat/completions", recorded(state, observe, create))
}
fn message_routes(
router: Routes,
state: &AppState,
observe: &crate::request_log::Observe,
) -> Routes {
let count = admitted(state, post(crate::messages::count_tokens))
.layer(middleware::from_fn(crate::messages::protocol));
let create = admitted(state, post(crate::messages::create))
.layer(middleware::from_fn(crate::messages::protocol));
router
.route("/v1/messages/count_tokens", count)
.route("/v1/messages", recorded(state, observe, create))
fn message_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
let count =
admitted(state, post(crate::messages::count_tokens)).layer(middleware::from_fn(crate::messages::protocol));
let create = admitted(state, post(crate::messages::create)).layer(middleware::from_fn(crate::messages::protocol));
router.route("/v1/messages/count_tokens", count).route("/v1/messages", recorded(state, observe, create))
}
/// The request monitor, the lifecycle, the stored responses.
@@ -102,14 +76,8 @@ fn admin_routes(router: Routes) -> Routes {
router
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/v1/responses/{id}", get(responses::retrieve).delete(responses::delete))
.route("/v1/responses/{id}/input_items", get(responses::input_items))
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
}
@@ -125,14 +93,8 @@ pub fn router(state: AppState) -> Router {
admin_routes(message_routes(routes, &state, &observe))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.http.api_key.clone(),
crate::auth::authorize,
))
.layer(middleware::from_fn_with_state(state.http.api_key.clone(), crate::auth::authorize))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.http.cors.clone(),
crate::server_api::cors_layer,
))
.layer(middleware::from_fn_with_state(state.http.cors.clone(), crate::server_api::cors_layer))
.with_state(state)
}
+3 -10
View File
@@ -64,8 +64,7 @@ pub struct ModelView {
pub vision: Option<SharedVisionEncoder>,
/// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`).
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`
/// (`docs/memory-safety.md`).
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`.
pub memory: Arc<crate::memory_view::MemoryView>,
}
@@ -107,11 +106,7 @@ impl Default for EngineLink {
impl Default for HttpPolicy {
fn default() -> Self {
Self {
api_key: None,
cors: Arc::new(Default::default()),
trusted_origins: Arc::new(Vec::new()),
}
Self { api_key: None, cors: Arc::new(Default::default()), trusted_origins: Arc::new(Vec::new()) }
}
}
@@ -133,9 +128,7 @@ impl Default for Services {
fn default() -> Self {
let clock = SystemClock::shared();
Self {
responses: responses::HistoryResponseStore::shared(
responses::ResponseHistory::default(),
),
responses: responses::HistoryResponseStore::shared(responses::ResponseHistory::default()),
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
+12 -46
View File
@@ -19,17 +19,9 @@ async fn assert_wrong_pids_refused(
state: &AppState,
(path, initial): (&str, bool),
) {
for (value, status) in [
("0".to_string(), 400),
("bad".into(), 400),
((std::process::id() + 1).to_string(), 409),
] {
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", value)
.send()
.await
.unwrap();
for (value, status) in [("0".to_string(), 400), ("bad".into(), 400), ((std::process::id() + 1).to_string(), 409)] {
let response =
client.post(format!("{url}/admin/{path}")).header("x-strata-expected-pid", value).send().await.unwrap();
assert_eq!(response.status().as_u16(), status);
assert_eq!(state.lifecycle.snapshot().draining, initial);
}
@@ -59,8 +51,7 @@ async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let value: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
let value: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(value["server_pid"], std::process::id());
assert_eq!(value["service"], "leleka-control-plane");
assert_eq!(value["draining"], !initial);
@@ -70,13 +61,8 @@ async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation()
}
async fn assert_drain_twice(client: &reqwest::Client, url: &str) {
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/drain"))
.send()
.await
.unwrap();
let data: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
let response = client.post(format!("{url}/admin/drain")).send().await.unwrap();
let data: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(data["draining"], true);
assert_eq!(data["drained"], true);
}
@@ -98,25 +84,15 @@ async fn assert_draining_refuses_unparsed(client: &reqwest::Client, url: &str, s
async fn assert_not_drained_while_busy(state: &AppState) {
let job = state.lifecycle.generation();
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
assert_eq!(lifecycle_status(State(state.clone())).await.0["drained"], false);
drop(job);
state.engine.worker.write().await.state = WorkerState::Restarting;
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
assert_eq!(lifecycle_status(State(state.clone())).await.0["drained"], false);
}
async fn assert_resume_is_idempotent(client: &reqwest::Client, url: &str) {
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/resume"))
.send()
.await
.unwrap();
let response = client.post(format!("{url}/admin/resume")).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
@@ -151,11 +127,7 @@ async fn queue_one_command(sender: &tokio::sync::mpsc::Sender<GenerationCommand>
.send(GenerationCommand {
queue: None,
activity: None,
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
..Default::default()
},
request: crate::wire::Generate { token_ids: vec![10], max_new: 1, ..Default::default() },
result: crate::worker::GenerationResult::Buffered(result),
})
.await
@@ -175,10 +147,7 @@ fn assert_busy_metrics(body: &serde_json::Value) {
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = tokio::sync::mpsc::channel(2);
let state = AppState {
engine: EngineLink {
client: Some(ChannelEngine::shared(sender.clone())),
..Default::default()
},
engine: EngineLink { client: Some(ChannelEngine::shared(sender.clone())), ..Default::default() },
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
@@ -193,10 +162,7 @@ async fn metrics_expose_activity_without_changing_discovery() {
assert_eq!(response.headers()["content-type"], "application/json");
let body: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_busy_metrics(&body);
assert_eq!(
serde_json::to_value(status(State(state.clone())).await.0).unwrap(),
initial_status
);
assert_eq!(serde_json::to_value(status(State(state.clone())).await.0).unwrap(), initial_status);
receiver.recv().await.unwrap();
assert_eq!(metrics_document(&state, false).await["queue_used"], 0);
server.abort();
+6 -19
View File
@@ -26,16 +26,13 @@ pub fn validate(bundles: &[AssetBundle]) -> Result<()> {
for path in [&bundle.manifest, &bundle.directory] {
if !path.is_absolute()
|| path.file_name().is_none()
|| path
.components()
.any(|part| matches!(part, Component::ParentDir))
|| path.components().any(|part| matches!(part, Component::ParentDir))
{
return Err("asset paths must be absolute, non-root paths without '..'".into());
}
}
if bundles[..index].iter().any(|other| {
other.directory.starts_with(&bundle.directory)
|| bundle.directory.starts_with(&other.directory)
other.directory.starts_with(&bundle.directory) || bundle.directory.starts_with(&other.directory)
}) {
return Err("asset bundle destinations must not overlap".into());
}
@@ -58,15 +55,9 @@ pub async fn provision(bundles: &[AssetBundle]) -> Result<()> {
}
async fn ensure(bundle: &AssetBundle, manifest: &model::Manifest) -> Result<()> {
let parent = bundle
.directory
.parent()
.ok_or("asset directory has no parent")?;
let parent = bundle.directory.parent().ok_or("asset directory has no parent")?;
fs::create_dir_all(parent)?;
let name = bundle
.directory
.file_name()
.ok_or("asset directory has no name")?;
let name = bundle.directory.file_name().ok_or("asset directory has no name")?;
let sibling = |suffix: &str| sibling_path(parent, name, suffix);
let _lock = lock_destination(&sibling(".strata-lock"))?;
if directory_exists(&bundle.directory)? {
@@ -119,9 +110,7 @@ fn lock_destination(path: &Path) -> Result<File> {
if !lock.metadata()?.is_file() {
return Err("asset lock must be a regular file".into());
}
lock.try_lock().map_err(
|_| "asset bundle is busy or cannot be locked; retry after preparation finishes",
)?;
lock.try_lock().map_err(|_| "asset bundle is busy or cannot be locked; retry after preparation finishes")?;
Ok(lock)
}
@@ -153,9 +142,7 @@ async fn verify_bundle(manifest: &model::Manifest, directory: &Path) -> Result<(
for entry in fs::read_dir(directory)? {
let name = entry?.file_name();
if !manifest.files.iter().any(|file| name == file.name.as_str()) {
return Err(
"asset bundle contains files absent from its manifest; use a new directory".into(),
);
return Err("asset bundle contains files absent from its manifest; use a new directory".into());
}
}
model::verify(manifest, directory).await
+13 -56
View File
@@ -87,9 +87,7 @@ pub(crate) fn read_token(path: &Path) -> Result<String, Box<dyn std::error::Erro
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(
"API key file must not grant group/other permissions (use chmod 600)".into(),
);
return Err("API key file must not grant group/other permissions (use chmod 600)".into());
}
}
let mut bytes = Vec::new();
@@ -101,36 +99,20 @@ pub(crate) fn parse_token(bytes: &[u8]) -> Result<String, Box<dyn std::error::Er
if bytes.len() > 514 {
return Err("API key file exceeds 514 bytes".into());
}
let value = std::str::from_utf8(bytes)
.map_err(|_| "API key must contain printable ASCII")?
.trim_end_matches(['\r', '\n']);
let value =
std::str::from_utf8(bytes).map_err(|_| "API key must contain printable ASCII")?.trim_end_matches(['\r', '\n']);
ApiKey::from_token(value)?;
Ok(value.to_owned())
}
pub async fn authorize(
State(key): State<Option<Arc<ApiKey>>>,
request: Request,
next: Next,
) -> Response {
let messages = matches!(
request.uri().path(),
"/v1/messages" | "/v1/messages/count_tokens"
);
pub async fn authorize(State(key): State<Option<Arc<ApiKey>>>, request: Request, next: Next) -> Response {
let messages = matches!(request.uri().path(), "/v1/messages" | "/v1/messages/count_tokens");
if !matches!(request.uri().path(), "/health" | "/api/health")
&& key.as_ref().is_some_and(|key| {
if messages {
!key.accepts_messages(request.headers())
} else {
!key.accepts(request.headers())
}
if messages { !key.accepts_messages(request.headers()) } else { !key.accepts(request.headers()) }
})
{
return (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
Json(invalid_key_body(messages)),
)
return (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")], Json(invalid_key_body(messages)))
.into_response();
}
next.run(request).await
@@ -168,14 +150,8 @@ mod tests {
headers.insert(header::AUTHORIZATION, value.parse().unwrap());
assert!(!key.accepts(&headers));
}
headers.insert(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
headers.append(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
headers.insert(header::AUTHORIZATION, format!("Bearer {KEY}").parse().unwrap());
headers.append(header::AUTHORIZATION, format!("Bearer {KEY}").parse().unwrap());
assert!(!key.accepts(&headers));
}
@@ -191,12 +167,7 @@ mod tests {
"/admin/lifecycle",
"/unknown",
] {
let response = client
.post(format!("{url}{path}"))
.body("not json")
.send()
.await
.unwrap();
let response = client.post(format!("{url}{path}")).body("not json").send().await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer");
assert!(!response.text().await.unwrap().contains(KEY));
@@ -204,12 +175,7 @@ mod tests {
}
async fn assert_authorized_requests_pass(client: &reqwest::Client, url: &str) {
let response = client
.get(format!("{url}/status"))
.bearer_auth(KEY)
.send()
.await
.unwrap();
let response = client.get(format!("{url}/status")).bearer_auth(KEY).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(!response.text().await.unwrap().contains(KEY));
let response = client
@@ -234,19 +200,10 @@ mod tests {
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let server =
tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let server = tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let client = reqwest::Client::new();
assert_protected_paths_are_unauthorized(&client, &url).await;
assert_eq!(
client
.get(format!("{url}/health"))
.send()
.await
.unwrap()
.status(),
StatusCode::OK
);
assert_eq!(client.get(format!("{url}/health")).send().await.unwrap().status(), StatusCode::OK);
assert_authorized_requests_pass(&client, &url).await;
server.abort();
}
+1 -4
View File
@@ -39,10 +39,7 @@ use tokio::{
use crate::{
tokenizer::Tokenizer,
wire::{Done, Event, Finish, Generate},
worker::{
Control, GenerationCommand, LoadReply, WorkerState, WorkerStatus, deliver, finish,
send_failure, update,
},
worker::{Control, GenerationCommand, LoadReply, WorkerState, WorkerStatus, deliver, finish, send_failure, update},
};
/// Literals that end the text, as the ids `<|im_end|>` / `<|endoftext|>` do on the stdio wire.
+19 -63
View File
@@ -77,11 +77,7 @@ impl AttachLoop {
pub(super) async fn run(&mut self) {
loop {
let state = if self.attached_before {
WorkerState::Restarting
} else {
WorkerState::Starting
};
let state = if self.attached_before { WorkerState::Restarting } else { WorkerState::Starting };
update(&self.status, state, None).await;
// Fail what queued up while the engine was away; nothing is replayed.
while let Ok(command) = self.requests.try_recv() {
@@ -113,26 +109,14 @@ impl AttachLoop {
let model = self.config.model.clone();
let runtime = self.config.runtime.clone();
match on_engine(&self.engine, move |backend| backend.load(model, runtime)).await {
Ok(Ok(loaded))
if loaded
.validate_for_load(&self.config.model, &self.config.runtime)
.is_ok() =>
{
Ok(Ok(loaded)) if loaded.validate_for_load(&self.config.model, &self.config.runtime).is_ok() => {
return Some(loaded);
}
Ok(Ok(_)) => {
crate::elog!("the engine returned a load result that does not match the request")
}
Ok(Err(error)) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Err(error) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Ok(Err(error)) => leleka_obs::info("api", "engine_wait", &[("reason", error.to_string().as_str().into())]),
Err(error) => leleka_obs::info("api", "engine_wait", &[("reason", error.to_string().as_str().into())]),
}
None
}
@@ -160,10 +144,9 @@ impl AttachLoop {
fn on_control_detached(&mut self, message: Option<Control>) {
match message {
Some(Control::Load { reply }) => self.waiting.push(reply),
Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable(
reply,
"the worker is not attached to the engine",
),
Some(Control::Reconfigure { reply, .. }) => {
crate::worker::reconfigure_unavailable(reply, "the worker is not attached to the engine")
}
Some(Control::Unload { reply, .. }) => {
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
}
@@ -191,12 +174,7 @@ impl AttachLoop {
/// The status of a worker whose engine holds the model.
async fn publish_ready_status(&self) {
update(
&self.status,
WorkerState::Ready,
Some(self.config.max_context),
)
.await;
update(&self.status, WorkerState::Ready, Some(self.config.max_context)).await;
self.status.write().await.output_cap = Some(self.config.max_output_tokens);
self.status.write().await.text_level_engine = true;
self.status.write().await.last_activity = Some(Instant::now());
@@ -249,10 +227,7 @@ impl AttachLoop {
/// Ask the engine whether the configured model is still loaded.
async fn engine_reports_model(&self) -> bool {
let wanted = self.config.model.clone();
let present = on_engine(&self.engine, move |backend| {
backend.capabilities().supports(&wanted)
})
.await;
let present = on_engine(&self.engine, move |backend| backend.capabilities().supports(&wanted)).await;
present == Ok(true)
}
@@ -272,9 +247,7 @@ impl AttachLoop {
Some(Control::Load { reply }) => {
let _ = reply.send(Ok(()));
}
Some(Control::Reconfigure { settings, reply }) => {
self.reconfigure(settings, reply).await
}
Some(Control::Reconfigure { settings, reply }) => self.reconfigure(settings, reply).await,
Some(Control::Unload { reply, .. }) => {
// The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP.
let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported);
@@ -283,28 +256,19 @@ impl AttachLoop {
}
}
async fn reconfigure(
&self,
settings: String,
reply: tokio::sync::oneshot::Sender<Result<String, (u16, String)>>,
) {
async fn reconfigure(&self, settings: String, reply: tokio::sync::oneshot::Sender<Result<String, (u16, String)>>) {
// Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds.
let answer =
match on_engine(&self.engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((error_status(error.code), error.message)),
Err(message) => Err((500, message)),
};
let answer = match on_engine(&self.engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((error_status(error.code), error.message)),
Err(message) => Err((500, message)),
};
let _ = reply.send(answer);
refresh_prefix_view(&self.engine, &self.config).await;
}
/// One queued request; `Some` ends the serving stretch.
async fn on_request(
&mut self,
command: Option<GenerationCommand>,
loaded: &api::LoadedModel,
) -> Option<Flow> {
async fn on_request(&mut self, command: Option<GenerationCommand>, loaded: &api::LoadedModel) -> Option<Flow> {
let Some(mut command) = command else {
self.requests_closed = true;
return None;
@@ -316,18 +280,10 @@ impl AttachLoop {
}
/// Serve a request nobody has abandoned and decide how the serving stretch goes on.
async fn serve_claimed(
&mut self,
mut command: GenerationCommand,
loaded: &api::LoadedModel,
) -> Option<Flow> {
async fn serve_claimed(&mut self, mut command: GenerationCommand, loaded: &api::LoadedModel) -> Option<Flow> {
self.status.write().await.last_activity = Some(command.request.obs.now());
let _activity = command.activity.take();
let ctx = Context {
engine: &self.engine,
config: &self.config,
status: &self.status,
};
let ctx = Context { engine: &self.engine, config: &self.config, status: &self.status };
let served = serve_one(ctx, &mut self.shutdown, &mut command, loaded).await;
self.after_request(served, &command).await
}
+5 -26
View File
@@ -118,26 +118,15 @@ impl Ending<'_> {
}
async fn failed(&mut self, message: String, code: api::ErrorCode) {
let message = if message.is_empty() {
format!("engine generation failed ({code:?})")
} else {
message
};
let message = if message.is_empty() { format!("engine generation failed ({code:?})") } else { message };
self.fail(message).await;
}
}
/// How long the generation waited for its first text and how long it then decoded, in milliseconds.
fn timings(state: &Conclusion<'_>, ended: Instant) -> (f64, f64) {
let prompt_ms = state
.first_delta
.unwrap_or(ended)
.duration_since(state.started)
.as_secs_f64()
* 1000.0;
let decode_ms = state
.first_delta
.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
let prompt_ms = state.first_delta.unwrap_or(ended).duration_since(state.started).as_secs_f64() * 1000.0;
let decode_ms = state.first_delta.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
(prompt_ms, decode_ms)
}
@@ -151,19 +140,9 @@ pub(super) async fn conclude(
) -> Served {
let (prompt_ms, decode_ms) = timings(&state, command.request.obs.now());
let disconnected = matches!(state.cancel, Some(Cancel::Client)) || command.result.is_closed();
let mut ending = Ending {
command,
status,
buffered,
state,
prompt_ms,
decode_ms,
disconnected,
};
let mut ending = Ending { command, status, buffered, state, prompt_ms, decode_ms, disconnected };
match terminal {
api::GenerationTerminal::Completed { reason, usage } => {
ending.completed(reason, usage).await
}
api::GenerationTerminal::Completed { reason, usage } => ending.completed(reason, usage).await,
api::GenerationTerminal::Cancelled => ending.cancelled().await,
api::GenerationTerminal::Failed { message, code, .. } => ending.failed(message, code).await,
}
@@ -17,9 +17,7 @@ pub(super) async fn on_engine<T: Send + 'static>(
) -> Result<T, String> {
let engine = Arc::clone(engine);
tokio::task::spawn_blocking(move || {
let mut guard = engine
.lock()
.map_err(|_| "engine state is poisoned".to_owned())?;
let mut guard = engine.lock().map_err(|_| "engine state is poisoned".to_owned())?;
Ok(call(&mut **guard))
})
.await
@@ -29,15 +27,13 @@ pub(super) async fn on_engine<T: Send + 'static>(
/// The prompt as text, or why the engine would not see exactly these tokens.
pub(super) fn prompt_text(tokenizer: &Tokenizer, ids: &[u32]) -> Result<String, String> {
let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?;
let text = String::from_utf8(bytes)
.map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let text =
String::from_utf8(bytes).map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let again = tokenizer.encode(&text, true).map_err(|e| e.to_string())?;
if again != ids {
return Err(
"the prompt tokens are not the canonical encoding of their text, so a text-level engine \
return Err("the prompt tokens are not the canonical encoding of their text, so a text-level engine \
would tokenize the prompt differently; refusing to serve different tokens than were counted"
.to_owned(),
);
.to_owned());
}
Ok(text)
}
@@ -65,16 +61,10 @@ fn refuse_unsupported(request: &Generate) -> Result<(), String> {
.to_owned());
}
if request.tune.is_some() {
return Err(
"strata_tune is an engine-process setting and is not part of the engine contract"
.to_owned(),
);
return Err("strata_tune is an engine-process setting and is not part of the engine contract".to_owned());
}
if request.cvec.is_some() {
return Err(
"experimental_speed_projection (control vectors) is not part of the engine contract"
.to_owned(),
);
return Err("experimental_speed_projection (control vectors) is not part of the engine contract".to_owned());
}
Ok(())
}
@@ -112,9 +102,7 @@ async fn marked_or_decoded_prompt(
tokio::task::spawn_blocking(move || match marked {
Some(text)
if tokenizer.marks().has_marks(&text)
&& tokenizer
.encode_marked(&text)
.is_ok_and(|encoded| encoded == ids) =>
&& tokenizer.encode_marked(&text).is_ok_and(|encoded| encoded == ids) =>
{
Ok(text.to_string())
}
@@ -130,13 +118,7 @@ async fn engine_prompt(config: &BackendWorkerConfig, request: &Generate) -> Resu
let prompt = match &request.prompt_text {
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still
// decode to it (a table walk over the ids, well under a millisecond for a whole conversation).
Some(text)
if config
.tokenizer
.decodes_to(&request.token_ids, text.as_bytes()) =>
{
text.to_string()
}
Some(text) if config.tokenizer.decodes_to(&request.token_ids, text.as_bytes()) => text.to_string(),
// Control-token text inside a message travels marked (`LiteralMarks`), and the engine reads the marks
// (`encode_marked`): the text is handed over if that encoding is exactly the ids that were counted.
// Anything else is decoded and must be the canonical encoding of its own text, or it is refused.
@@ -142,10 +142,7 @@ impl<'a> Run<'a> {
first_delta: None,
delivered: 0,
last_progress: Instant::now(),
deadline: ctx
.config
.generation_timeout
.map(|limit| request.started + limit),
deadline: ctx.config.generation_timeout.map(|limit| request.started + limit),
drain_deadline: None,
}
}
@@ -281,9 +278,7 @@ impl<'a> Run<'a> {
}
async fn deliver_text(&mut self, emit: &str) -> Result<(), String> {
let ids = crate::stage_trace::time("delta_retokenize", || {
text_tokens(&self.ctx.config.tokenizer, emit)
})?;
let ids = crate::stage_trace::time("delta_retokenize", || text_tokens(&self.ctx.config.tokenizer, emit))?;
for id in ids {
self.delivered += 1;
deliver(self.command, &mut self.buffered, Event::Token(id)).await;
@@ -35,10 +35,7 @@ async fn call_start(
) -> Result<Result<api::GenerationStream, api::BackendError>, String> {
let _span = crate::stage_trace::span("engine_start");
let model = loaded.clone();
on_engine(engine, move |backend| {
backend.start_generation(&model, request)
})
.await
on_engine(engine, move |backend| backend.start_generation(&model, request)).await
}
async fn count_failed_start(status: &RwLock<WorkerStatus>) {
@@ -58,11 +55,7 @@ async fn answer_refused_start(
}
/// The engine could not be asked at all: fail the request; the engine is lost.
async fn answer_lost_start(
status: &RwLock<WorkerStatus>,
command: &mut GenerationCommand,
message: String,
) -> Served {
async fn answer_lost_start(status: &RwLock<WorkerStatus>, command: &mut GenerationCommand, message: String) -> Served {
count_failed_start(status).await;
fail_command(command, message.clone()).await;
Served::Lost(message)
@@ -70,11 +63,7 @@ async fn answer_lost_start(
/// How the worker goes on after the engine refused a generation: it is lost only when the engine itself is unavailable.
fn served_after_refusal(error: &api::BackendError, message: String) -> Served {
if error.code == api::ErrorCode::BackendUnavailable {
Served::Lost(message)
} else {
Served::Done
}
if error.code == api::ErrorCode::BackendUnavailable { Served::Lost(message) } else { Served::Done }
}
fn log_generation_start(start_ms: u128, counted_input: u64, max_new: u32) {
@@ -105,14 +94,7 @@ async fn start_engine(
let start = call_start(engine, loaded, request).await;
log_generation_start(start_ms, counted_input, max_new);
match start {
Ok(Ok(stream)) => Ok((
stream,
Started {
id,
counted_input,
started,
},
)),
Ok(Ok(stream)) => Ok((stream, Started { id, counted_input, started })),
Ok(Err(error)) => Err(answer_refused_start(status, command, &error).await),
Err(message) => Err(answer_lost_start(status, command, message).await),
}
@@ -131,13 +113,10 @@ pub(super) async fn serve_one_inner(
return Served::Done;
}
};
let (stream, started) =
match start_engine(ctx.engine, ctx.status, command, loaded, request).await {
Ok(started) => started,
Err(served) => return served,
};
let (stream, started) = match start_engine(ctx.engine, ctx.status, command, loaded, request).await {
Ok(started) => started,
Err(served) => return served,
};
let events = pump_events(stream);
Run::new(ctx, shutdown, command, events, started)
.run()
.await
Run::new(ctx, shutdown, command, events, started).run().await
}
@@ -15,29 +15,18 @@ pub async fn run_backend_worker(
inbox: WorkerInbox,
) {
let engine: Engine = Arc::new(Mutex::new(backend));
AttachLoop::new(engine, config, status, shutdown, inbox)
.run()
.await
AttachLoop::new(engine, config, status, shutdown, inbox).run().await
}
/// Copy the engine's prefix-cache summary into the view the status endpoint reads.
pub(super) async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) {
if let Some(view) = &config.prefix_view {
let summary = on_engine(engine, |backend| backend.prefix_cache_summary())
.await
.ok()
.flatten();
let summary = on_engine(engine, |backend| backend.prefix_cache_summary()).await.ok().flatten();
view.set(summary);
}
if let Some(view) = &config.memory_view {
let report = on_engine(engine, |backend| backend.memory_report())
.await
.ok()
.flatten();
let report = on_engine(engine, |backend| backend.memory_report()).await.ok().flatten();
view.set(report);
let telemetry = on_engine(engine, |backend| backend.telemetry_report())
.await
.ok()
.flatten();
let telemetry = on_engine(engine, |backend| backend.telemetry_report()).await.ok().flatten();
view.set_telemetry(telemetry);
}
}
+4 -14
View File
@@ -1,9 +1,7 @@
use std::{env, fs, process::ExitCode};
use leleka_control_plane::responses::{CreateRequest, OutputItem, ResponseIdentity, ResponseTrace, Usage};
use serde::Deserialize;
use leleka_control_plane::responses::{
CreateRequest, OutputItem, ResponseIdentity, ResponseTrace, Usage,
};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -30,11 +28,7 @@ const USAGE: &str = "usage: replay-responses [--sse] FIXTURE.json";
fn parse_args() -> Result<(bool, String), String> {
let mut args = env::args().skip(1);
let first = args.next().ok_or(USAGE)?;
let (sse, path) = if first == "--sse" {
(true, args.next().ok_or(USAGE)?)
} else {
(false, first)
};
let (sse, path) = if first == "--sse" { (true, args.next().ok_or(USAGE)?) } else { (false, first) };
if args.next().is_some() {
return Err(USAGE.to_owned());
}
@@ -44,8 +38,7 @@ fn parse_args() -> Result<(bool, String), String> {
fn run() -> Result<(), String> {
let (sse, path) = parse_args()?;
let source = fs::read_to_string(&path).map_err(|error| format!("{path}: {error}"))?;
let fixture: Fixture = serde_json::from_str(&source)
.map_err(|error| format!("invalid fixture {path}: {error}"))?;
let fixture: Fixture = serde_json::from_str(&source).map_err(|error| format!("invalid fixture {path}: {error}"))?;
let identity = ResponseIdentity::new(&fixture.id, fixture.created_at, fixture.completed_at);
let trace = ResponseTrace::build(&fixture.request, &fixture.items, fixture.usage, identity)?;
if sse {
@@ -53,10 +46,7 @@ fn run() -> Result<(), String> {
print!("{frame}");
}
} else {
println!(
"{}",
serde_json::to_string_pretty(&trace.response).map_err(|error| error.to_string())?
);
println!("{}", serde_json::to_string_pretty(&trace.response).map_err(|error| error.to_string())?);
}
Ok(())
}
@@ -38,32 +38,18 @@ fn collect_output(response: &Value) -> (String, Vec<Value>) {
pub(super) fn completion(response: &Value) -> Value {
let (text, calls) = collect_output(response);
let content = if text.is_empty() && !calls.is_empty() {
Value::Null
} else {
json!(text)
};
let content = if text.is_empty() && !calls.is_empty() { Value::Null } else { json!(text) };
let mut message = json!({"role":"assistant","content":content,"refusal":null});
if !calls.is_empty() {
message["tool_calls"] = json!(calls);
}
let mut value = identity(response, "chat.completion");
value["choices"] =
json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]);
value["choices"] = json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]);
value["usage"] = usage(response);
value
}
pub(super) fn error(
status: StatusCode,
code: &str,
param: Option<&str>,
message: &str,
) -> Response {
let kind = if status.is_server_error() {
"server_error"
} else {
"invalid_request_error"
};
pub(super) fn error(status: StatusCode, code: &str, param: Option<&str>, message: &str) -> Response {
let kind = if status.is_server_error() { "server_error" } else { "invalid_request_error" };
let body = json!({"error":{"type":kind,"code":code,"param":param,"message":message}});
(status, Json(body)).into_response()
}
@@ -74,28 +60,15 @@ fn refuse(status: StatusCode, code: &str, param: Option<&str>, message: &str) ->
}
/// The chat request as a native request, with its sampling extensions, and whether to stream with usage.
fn parse_request(
body: Result<Json<Value>, JsonRejection>,
) -> Result<(Value, bool, bool), Box<Response>> {
fn parse_request(body: Result<Json<Value>, JsonRejection>) -> Result<(Value, bool, bool), Box<Response>> {
let Json(body) = body.map_err(|e| refuse(e.status(), "invalid_json", None, &e.to_string()))?;
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
let (body, extensions) = crate::sampling::split_extensions(body);
let request: Request = serde_json::from_value(body).map_err(|e| {
refuse(
StatusCode::BAD_REQUEST,
"invalid_request",
None,
&e.to_string(),
)
})?;
let (mut request, stream, include_usage) = request.into_responses().map_err(|(p, m)| {
refuse(
StatusCode::BAD_REQUEST,
"unsupported_chat_feature",
Some(p),
m,
)
})?;
let request: Request = serde_json::from_value(body)
.map_err(|e| refuse(StatusCode::BAD_REQUEST, "invalid_request", None, &e.to_string()))?;
let (mut request, stream, include_usage) = request
.into_responses()
.map_err(|(p, m)| refuse(StatusCode::BAD_REQUEST, "unsupported_chat_feature", Some(p), m))?;
for (key, value) in extensions {
request[key] = value;
}
@@ -112,22 +85,12 @@ async fn native_json(body: Body) -> Result<Value, Box<Response>> {
"native response could not be read within the adapter limit",
)
})?;
serde_json::from_slice(&bytes).map_err(|_| {
refuse(
StatusCode::BAD_GATEWAY,
"invalid_native_response",
None,
"native response was not JSON",
)
})
serde_json::from_slice(&bytes)
.map_err(|_| refuse(StatusCode::BAD_GATEWAY, "invalid_native_response", None, "native response was not JSON"))
}
/// A native refusal with the chat names of the parameters, keeping the `Retry-After` of the original.
fn refusal(
status: StatusCode,
mut value: Value,
retry_after: Option<axum::http::HeaderValue>,
) -> Response {
fn refusal(status: StatusCode, mut value: Value, retry_after: Option<axum::http::HeaderValue>) -> Response {
if let Some(param) = value["error"]["param"].as_str() {
let mapped = match param {
"input" => "messages",
@@ -139,17 +102,12 @@ fn refusal(
}
let mut refusal = (status, Json(value)).into_response();
if let Some(retry_after) = retry_after {
refusal
.headers_mut()
.insert(axum::http::header::RETRY_AFTER, retry_after);
refusal.headers_mut().insert(axum::http::header::RETRY_AFTER, retry_after);
}
refusal
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
pub async fn create(State(state): State<AppState>, body: Result<Json<Value>, JsonRejection>) -> Response {
let (request, stream, include_usage) = match parse_request(body) {
Ok(parsed) => parsed,
Err(response) => return *response,
@@ -161,10 +119,7 @@ pub async fn create(
let status = response.status();
// a refusal that tells the client when to come back (503 memory_pressure) keeps its Retry-After through the
// re-wrapping below
let retry_after = response
.headers()
.get(axum::http::header::RETRY_AFTER)
.cloned();
let retry_after = response.headers().get(axum::http::header::RETRY_AFTER).cloned();
let value = match native_json(response.into_body()).await {
Ok(value) => value,
Err(response) => return *response,
@@ -181,10 +136,7 @@ impl Stream for Events {
}
}
pub(super) async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
sender
.send(Event::default().data(value.to_string()))
.await
.map_err(|_| "client disconnected")
sender.send(Event::default().data(value.to_string())).await.map_err(|_| "client disconnected")
}
pub(super) fn chunk(base: &Value, delta: Value, reason: Value, include_usage: bool) -> Value {
let mut v = base.clone();
@@ -212,10 +164,7 @@ impl Adapter<'_> {
}
async fn done_marker(&self) -> Result<(), &'static str> {
self.sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")
self.sender.send(Event::default().data("[DONE]")).await.map_err(|_| "client disconnected")
}
async fn created(&mut self, event: &Value) -> Result<(), &'static str> {
@@ -242,8 +191,7 @@ impl Adapter<'_> {
/// The finish chunk, the usage chunk when asked for, and the end marker.
async fn completed(&self, event: &Value) -> Result<(), &'static str> {
let base = self.base()?;
self.push(base, json!({}), json!(finish(&event["response"])))
.await?;
self.push(base, json!({}), json!(finish(&event["response"]))).await?;
if self.include_usage {
let mut v = base.clone();
v["choices"] = json!([]);
@@ -266,9 +214,7 @@ impl Adapter<'_> {
Some("response.output_item.done") if event["item"]["type"] == "function_call" => {
self.tool_call(event).await.map(|()| false)
}
Some("response.completed" | "response.incomplete") => {
self.completed(event).await.map(|()| true)
}
Some("response.completed" | "response.incomplete") => self.completed(event).await.map(|()| true),
Some("response.failed") => self.failed(event).await.map(|()| true),
_ => Ok(false),
}
@@ -281,15 +227,9 @@ pub(super) async fn adapt(
include_usage: bool,
) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut adapter = Adapter {
sender,
include_usage,
base: None,
calls: 0,
};
let mut adapter = Adapter { sender, include_usage, base: None, calls: 0 };
loop {
let event =
tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? };
let event = tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? };
if adapter.on_event(&event).await? {
return Ok(());
}
+1 -3
View File
@@ -14,7 +14,5 @@ pub(super) fn stream_response(mut body: Body, include_usage: bool) -> Response {
let _ = sender.send(Event::default().data("[DONE]")).await;
}
});
Sse::new(Events(received))
.keep_alive(crate::native_events::keep_alive())
.into_response()
Sse::new(Events(received)).keep_alive(crate::native_events::keep_alive()).into_response()
}
+1 -3
View File
@@ -36,7 +36,5 @@ async fn run_model_files(args: &[String]) -> Result<bool, BoxError> {
/// The `model` commands on KAR files: inspect, verify and overlay.
async fn run_kar(args: &[String]) -> Result<bool, BoxError> {
Ok(kar_inspect::run(args).await?
|| kar_verify::run(args).await?
|| kar_overlay::run(args).await?)
Ok(kar_inspect::run(args).await? || kar_verify::run(args).await? || kar_overlay::run(args).await?)
}
+6 -30
View File
@@ -22,12 +22,8 @@ pub async fn run(args: &[String]) -> Result<bool, BoxError> {
fn kar_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
("checksum-kar-preview", [path, tensor, level]) => {
Some(checksum_preview(path, tensor, level))
}
("checksum-kar-row", [path, tensor, level, row_flag, row_id])
if flags(&[(row_flag, "--row")]) =>
{
("checksum-kar-preview", [path, tensor, level]) => Some(checksum_preview(path, tensor, level)),
("checksum-kar-row", [path, tensor, level, row_flag, row_id]) if flags(&[(row_flag, "--row")]) => {
Some(checksum_row(path, tensor, level, row_id))
}
("inspect-kar", [path]) => Some(inspect(path)),
@@ -48,19 +44,7 @@ fn plan_commands(action: &str, rest: &[String]) -> Outcome {
}
fn overlay_memory_command(rest: &[String]) -> Outcome {
let [
bf,
base,
of,
overlay,
blf,
base_level,
olf,
overlay_level,
budget_flag,
budget,
] = rest
else {
let [bf, base, of, overlay, blf, base_level, olf, overlay_level, budget_flag, budget] = rest else {
return None;
};
let named = [
@@ -88,10 +72,7 @@ fn checksum_preview(path: &str, tensor: &str, level: &str) -> Result<(), BoxErro
fn checksum_row(path: &str, tensor: &str, level: &str, row_id: &str) -> Result<(), BoxError> {
let row_id: u32 = row_id.parse()?;
let values = kar::decode_tensor_row(Path::new(path), tensor, level.parse()?, row_id)?;
println!(
"tensor={tensor} row_id={row_id} elements={} level={level}",
values.len()
);
println!("tensor={tensor} row_id={row_id} elements={} level={level}", values.len());
print_checksum(&values);
Ok(())
}
@@ -100,10 +81,7 @@ fn inspect(path: &str) -> Result<(), BoxError> {
let summary = kar::inspect(Path::new(path))?;
println!("KAR-2: {path}");
println!("size: {} bytes", summary.archive_bytes);
println!(
"tensors: {}; elements: {}",
summary.tensor_count, summary.total_elements
);
println!("tensors: {}; elements: {}", summary.tensor_count, summary.total_elements);
println!("source elements: {}", summary.source_total_elements);
println!("accounted bpw: {}", summary.accounted_bpw);
println!("source SHA-256: {}", hex::encode(summary.source_digest));
@@ -115,9 +93,7 @@ fn inspect(path: &str) -> Result<(), BoxError> {
/// The GPU budget in bytes from its `--budget-mib` text.
fn budget_bytes(budget: &str) -> Result<u64, BoxError> {
let budget_mib: u64 = budget.parse()?;
Ok(budget_mib
.checked_mul(1 << 20)
.ok_or("GPU budget overflow")?)
Ok(budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?)
}
fn plan_memory(path: &str, level: &str, budget: &str) -> Result<(), BoxError> {
+8 -31
View File
@@ -20,28 +20,16 @@ pub async fn run(args: &[String]) -> Result<bool, BoxError> {
async fn overlay_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
("prepare-kar-overlay", [spec, sf, dir, bf, base, cf, candidates, of, destination])
if flags(&[
(sf, "--source-dir"),
(bf, "--base"),
(cf, "--candidates"),
(of, "--output"),
]) =>
if flags(&[(sf, "--source-dir"), (bf, "--base"), (cf, "--candidates"), (of, "--output")]) =>
{
Some(prepare(spec, dir, base, candidates, destination).await)
}
("compare-kar-overlay", [spec, sf, dir, bf, base, of, overlay, outf, report_path])
if flags(&[
(sf, "--source-dir"),
(bf, "--base"),
(of, "--overlay"),
(outf, "--output"),
]) =>
if flags(&[(sf, "--source-dir"), (bf, "--base"), (of, "--overlay"), (outf, "--output")]) =>
{
Some(compare(spec, dir, base, overlay, report_path).await)
}
("resolve-kar-overlay", [bf, base, of, overlay])
if flags(&[(bf, "--base"), (of, "--overlay")]) =>
{
("resolve-kar-overlay", [bf, base, of, overlay]) if flags(&[(bf, "--base"), (of, "--overlay")]) => {
Some(resolve(base, overlay))
}
_ => None,
@@ -64,15 +52,9 @@ async fn prepare(
Path::new(destination),
)?;
println!("EXPERIMENTAL KAR precision overlay: {destination}");
println!(
"records: {}; bytes: {}",
result.record_count, result.archive_bytes
);
println!("records: {}; bytes: {}", result.record_count, result.archive_bytes);
println!("overlay SHA-256: {}", hex::encode(result.archive_sha256));
println!(
"maximum selected-record relative L2: {:.8}",
result.maximum_relative_l2
);
println!("maximum selected-record relative L2: {:.8}", result.maximum_relative_l2);
println!("provenance: {}", result.provenance_path.display());
println!("not eligible for serving without model-quality and GPU gates");
Ok(())
@@ -86,12 +68,8 @@ async fn compare(
report_path: &str,
) -> Result<(), BoxError> {
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let comparison = kar_overlay::compare(
&manifest,
Path::new(source_dir),
Path::new(base_archive),
Path::new(overlay_archive),
)?;
let comparison =
kar_overlay::compare(&manifest, Path::new(source_dir), Path::new(base_archive), Path::new(overlay_archive))?;
kar_overlay::write_comparison(Path::new(report_path), &comparison)?;
println!("complete selected-tensor L2/L3 comparison: {report_path}");
println!("records: {}", comparison.records.len());
@@ -100,8 +78,7 @@ async fn compare(
}
fn resolve(base_archive: &str, overlay_archive: &str) -> Result<(), BoxError> {
let resolution =
kar_overlay::resolve_verified(Path::new(base_archive), Path::new(overlay_archive))?;
let resolution = kar_overlay::resolve_verified(Path::new(base_archive), Path::new(overlay_archive))?;
println!("{}", serde_json::to_string_pretty(&resolution)?);
Ok(())
}
+13 -55
View File
@@ -27,10 +27,7 @@ pub async fn run(args: &[String]) -> Result<bool, BoxError> {
fn print_preview_summary(kind: &str, archive: &str, summary: &kar::Summary) {
println!("verified {kind}: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
}
fn print_preview_tail(identity: &str) {
@@ -41,9 +38,7 @@ fn print_preview_tail(identity: &str) {
async fn verify_single(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
("verify-kar", [path]) => Some(verify_kar(path)),
("verify-kar", [path, mf, spec, sf, dir])
if flags(&[(mf, "--manifest"), (sf, "--source-dir")]) =>
{
("verify-kar", [path, mf, spec, sf, dir]) if flags(&[(mf, "--manifest"), (sf, "--source-dir")]) => {
Some(verify_kar_with_sources(path, spec, dir).await)
}
("verify-iq3-preview", [archive, sf, source]) if flags(&[(sf, "--source")]) => {
@@ -58,27 +53,17 @@ async fn verify_single(action: &str, rest: &[String]) -> Outcome {
fn verify_kar(path: &str) -> Result<(), BoxError> {
let summary = kar::verify(Path::new(path))?;
println!(
"verified KAR-2 metadata and {} payload CRCs",
summary.tensor_count
);
println!("verified KAR-2 metadata and {} payload CRCs", summary.tensor_count);
println!("source SHA-256: {}", hex::encode(summary.source_digest));
println!("source files not checked; use --manifest SPEC --source-dir DIR");
Ok(())
}
async fn verify_kar_with_sources(
path: &str,
manifest_spec: &str,
source_dir: &str,
) -> Result<(), BoxError> {
async fn verify_kar_with_sources(path: &str, manifest_spec: &str, source_dir: &str) -> Result<(), BoxError> {
let summary = kar::verify(Path::new(path))?;
let manifest = model::Manifest::from_spec(manifest_spec).await?;
kar::verify_source_files(&summary, &manifest, Path::new(source_dir))?;
println!(
"verified KAR-2 metadata, {} payload CRCs, and source identity",
summary.tensor_count
);
println!("verified KAR-2 metadata, {} payload CRCs, and source identity", summary.tensor_count);
Ok(())
}
@@ -109,12 +94,7 @@ async fn verify_sharded(action: &str, rest: &[String]) -> Outcome {
Some(verify_sharded_streamed(archive, spec, dir, levels).await)
}
("verify-sharded-streamed", [archive, mf, spec, sf, dir, lf, levels, pf, limit])
if flags(&[
(mf, "--manifest"),
(sf, "--source-dir"),
(lf, "--levels"),
(pf, "--ple-part-elements"),
]) =>
if flags(&[(mf, "--manifest"), (sf, "--source-dir"), (lf, "--levels"), (pf, "--ple-part-elements")]) =>
{
Some(verify_sharded_streamed_ple(archive, spec, dir, levels, limit).await)
}
@@ -122,14 +102,9 @@ async fn verify_sharded(action: &str, rest: &[String]) -> Outcome {
}
}
async fn verify_sharded_preview(
archive: &str,
manifest_spec: &str,
source_dir: &str,
) -> Result<(), BoxError> {
async fn verify_sharded_preview(archive: &str, manifest_spec: &str, source_dir: &str) -> Result<(), BoxError> {
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let summary =
prepare_preview::verify_sharded(&manifest, Path::new(source_dir), Path::new(archive))?;
let summary = prepare_preview::verify_sharded(&manifest, Path::new(source_dir), Path::new(archive))?;
print_preview_summary("sharded preview", archive, &summary);
print_preview_tail("manifest shards");
Ok(())
@@ -143,12 +118,8 @@ async fn verify_sharded_streamed(
) -> Result<(), BoxError> {
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let levels = levels.parse()?;
let summary = prepare_preview::verify_sharded_streamed(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels,
)?;
let summary =
prepare_preview::verify_sharded_streamed(&manifest, Path::new(source_dir), Path::new(archive), levels)?;
print_preview_summary("experimental streamed sharded KAR-2", archive, &summary);
print_preview_tail("manifest shards");
Ok(())
@@ -179,12 +150,7 @@ async fn verify_sharded_streamed_ple(
async fn analyze_sharded(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
("analyze-sharded-kar", [archive, mf, spec, sf, dir, lf, levels, of, report_path])
if flags(&[
(mf, "--manifest"),
(sf, "--source-dir"),
(lf, "--levels"),
(of, "--output"),
]) =>
if flags(&[(mf, "--manifest"), (sf, "--source-dir"), (lf, "--levels"), (of, "--output")]) =>
{
Some(analyze_sharded_kar(archive, spec, dir, levels, report_path).await)
}
@@ -211,12 +177,7 @@ async fn analyze_sharded_kar(
report_path: &str,
) -> Result<(), BoxError> {
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let report = kar_quality::analyze(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels.parse()?,
)?;
let report = kar_quality::analyze(&manifest, Path::new(source_dir), Path::new(archive), levels.parse()?)?;
kar_quality::write_report(Path::new(report_path), &report)?;
println!("sampled KAR reconstruction report: {report_path}");
println!("records: {}", report.records.len());
@@ -242,10 +203,7 @@ async fn analyze_previously_verified(
kar_quality::write_report(Path::new(report_path), &report)?;
println!("sampled KAR reconstruction report: {report_path}");
println!("records: {}", report.records.len());
println!(
"archive SHA-256 from previously verified provenance: {}",
report.archive_sha256
);
println!("archive SHA-256 from previously verified provenance: {}", report.archive_sha256);
println!("full archive and source hashes were not recomputed in this run");
println!("samples are not a full-tensor or model-quality gate");
Ok(())
+7 -28
View File
@@ -35,12 +35,7 @@ async fn ensure_sharded(action: &str, rest: &[String]) -> Outcome {
Some(ensure_streamed(spec, dir, destination, levels).await)
}
("ensure-sharded-streamed", [spec, sf, dir, of, destination, lf, levels, pf, limit])
if flags(&[
(sf, "--source-dir"),
(of, "--output"),
(lf, "--levels"),
(pf, "--ple-part-elements"),
]) =>
if flags(&[(sf, "--source-dir"), (of, "--output"), (lf, "--levels"), (pf, "--ple-part-elements")]) =>
{
Some(ensure_streamed_ple(spec, dir, destination, levels, limit).await)
}
@@ -49,10 +44,7 @@ async fn ensure_sharded(action: &str, rest: &[String]) -> Outcome {
}
fn print_maximum_relative_l2(result: &Preview) {
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
}
fn print_archive_digest(result: &Preview) {
@@ -104,12 +96,8 @@ async fn ensure_streamed(
.await?;
let source_bytes = sharded_source_bytes(&manifest)?;
match outcome {
model_pipeline::PreviewOutcome::Created(result) => {
print_streamed_created(destination, source_bytes, &result)
}
model_pipeline::PreviewOutcome::Reused(summary) => {
print_streamed_reused(destination, source_bytes, &summary)
}
model_pipeline::PreviewOutcome::Created(result) => print_streamed_created(destination, source_bytes, &result),
model_pipeline::PreviewOutcome::Reused(summary) => print_streamed_reused(destination, source_bytes, &summary),
}
println!("{NOT_ELIGIBLE}");
Ok(())
@@ -119,14 +107,8 @@ fn print_streamed_created(destination: &str, source_bytes: u64, result: &Preview
println!("created and verified experimental streamed KAR-2: {destination}");
println!("archive bytes: {}", result.archive.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
result.archive.archive_bytes as f64 / source_bytes as f64
);
println!(
"accounted bits per weight: {:.6}",
result.archive.accounted_bpw
);
println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64);
println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw);
print_archive_digest(result);
print_maximum_relative_l2(result);
print_top_tensor_distortions(&result.tensor_distortions);
@@ -136,10 +118,7 @@ fn print_streamed_reused(destination: &str, source_bytes: u64, summary: &kar::Su
println!("reused verified experimental streamed KAR-2: {destination}");
println!("archive bytes: {}", summary.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
summary.archive_bytes as f64 / source_bytes as f64
);
println!("archive/source ratio: {:.6}", summary.archive_bytes as f64 / source_bytes as f64);
println!("accounted bits per weight: {:.6}", summary.accounted_bpw);
println!("tensors: {}", summary.tensor_count);
}
+9 -38
View File
@@ -25,12 +25,8 @@ fn fixture_commands(action: &str, rest: &[String]) -> Outcome {
("export-tensor-f32", [source, tensor, flag, output]) if flags(&[(flag, "--output")]) => {
Some(export_tensor_f32(source, tensor, output))
}
("smoke-fixture", [flag, output]) if flags(&[(flag, "--output")]) => {
Some(smoke_fixture(output))
}
("ple-smoke-fixture", [flag, output]) if flags(&[(flag, "--output")]) => {
Some(ple_smoke_fixture(output))
}
("smoke-fixture", [flag, output]) if flags(&[(flag, "--output")]) => Some(smoke_fixture(output)),
("ple-smoke-fixture", [flag, output]) if flags(&[(flag, "--output")]) => Some(ple_smoke_fixture(output)),
_ => None,
}
}
@@ -42,64 +38,39 @@ async fn manifest_commands(action: &str, rest: &[String]) -> Outcome {
{
Some(prepare_native_pack(spec, source, output, options).await)
}
("fetch", [manifest, flag, output]) if flags(&[(flag, "--output")]) => {
Some(fetch(manifest, output).await)
}
("verify", [manifest, flag, output]) if flags(&[(flag, "--output")]) => {
Some(verify(manifest, output).await)
}
("fetch", [manifest, flag, output]) if flags(&[(flag, "--output")]) => Some(fetch(manifest, output).await),
("verify", [manifest, flag, output]) if flags(&[(flag, "--output")]) => Some(verify(manifest, output).await),
_ => None,
}
}
/// The options after `--output` of `prepare-native-pack`.
fn native_pack_options(
options: &[String],
) -> Result<leleka_control_plane::native_pack::Options, BoxError> {
fn native_pack_options(options: &[String]) -> Result<leleka_control_plane::native_pack::Options, BoxError> {
let mut pack = leleka_control_plane::native_pack::Options::default();
let mut options = options.iter();
while let Some(flag) = options.next() {
match flag.as_str() {
"--compat-bf16" => pack.compat_bf16 = true,
"--experts-bin" => pack.experts_bin = true,
"--base" => {
pack.base = Some(
options
.next()
.ok_or("--base needs a pack directory")?
.into(),
)
}
"--base" => pack.base = Some(options.next().ok_or("--base needs a pack directory")?.into()),
_ => return Err(format!("unknown prepare-native-pack option {flag}").into()),
}
}
Ok(pack)
}
async fn prepare_native_pack(
spec: &str,
source: &str,
output: &str,
options: &[String],
) -> Result<(), BoxError> {
async fn prepare_native_pack(spec: &str, source: &str, output: &str, options: &[String]) -> Result<(), BoxError> {
let manifest = leleka_control_plane::model::Manifest::from_spec(spec).await?;
let pack = native_pack_options(options)?;
println!(
"{}",
leleka_control_plane::native_pack::prepare_with(
&manifest,
Path::new(source),
Path::new(output),
&pack
)
.await?
leleka_control_plane::native_pack::prepare_with(&manifest, Path::new(source), Path::new(output), &pack).await?
);
Ok(())
}
fn export_tensor_f32(source: &str, tensor: &str, output: &str) -> Result<(), BoxError> {
let report =
leleka_control_plane::tensor_export::export(Path::new(source), tensor, Path::new(output))?;
let report = leleka_control_plane::tensor_export::export(Path::new(source), tensor, Path::new(output))?;
println!("{}", serde_json::to_string(&report)?);
Ok(())
}
+3 -8
View File
@@ -2,8 +2,8 @@
use std::path::Path;
use serde_json::{Value, json};
use leleka_control_plane::{BoxError, derived_iq3, derived_mixed, gguf, model};
use serde_json::{Value, json};
use super::args::{Outcome, flags, model_action};
@@ -37,9 +37,7 @@ async fn identity_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
("derive-iq3-identity", [path]) => Some(derive_iq3_identity(path)),
("derive-mixed-identity", [path]) => Some(derive_mixed_identity(path)),
("derive-sharded-identity", [spec, source_flag, dir])
if flags(&[(source_flag, "--source-dir")]) =>
{
("derive-sharded-identity", [spec, source_flag, dir]) if flags(&[(source_flag, "--source-dir")]) => {
Some(derive_sharded_identity(spec, dir).await)
}
_ => None,
@@ -57,10 +55,7 @@ fn inspect(path: &str) -> Result<(), BoxError> {
let summary = gguf::inspect(Path::new(path))?;
println!("GGUF v3: {path}");
println!("size: {} bytes", summary.file_size);
println!(
"tensors: {}; metadata: {}",
summary.tensors, summary.metadata
);
println!("tensors: {}; metadata: {}", summary.tensors, summary.metadata);
println!("data starts at byte {}", summary.data_start);
if let Some(architecture) = summary.architecture {
println!("architecture: {architecture}");
+15 -57
View File
@@ -33,24 +33,15 @@ fn print_archive_digest(result: &Preview) {
}
fn print_derived_digest(result: &Preview) {
println!(
"derived F32 SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
}
fn print_provenance(result: &Preview) {
println!(
"provenance: {}",
result.provenance_path.as_ref().unwrap().display()
);
println!("provenance: {}", result.provenance_path.as_ref().unwrap().display());
}
fn print_maximum_relative_l2(result: &Preview) {
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
}
const NOT_ELIGIBLE: &str = "not eligible for serving without a full-model quality gate";
@@ -77,13 +68,9 @@ fn prepare_single(action: &str, rest: &[String]) -> Outcome {
}
fn prepare_f32(source: &str, destination: &str, levels: &str) -> Result<(), BoxError> {
let result =
prepare_preview::prepare_f32(Path::new(source), Path::new(destination), levels.parse()?)?;
let result = prepare_preview::prepare_f32(Path::new(source), Path::new(destination), levels.parse()?)?;
print_header("EXPERIMENTAL F32 preview KAR-2", destination, &result);
println!(
"source SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("source SHA-256: {}", hex::encode(result.archive.source_digest));
print_archive_digest(&result);
print_maximum_relative_l2(&result);
println!("{NOT_ELIGIBLE}");
@@ -101,20 +88,14 @@ fn print_derived_preview(header: &str, destination: &str, result: &Preview) {
}
fn prepare_iq3(source: &str, destination: &str, levels: &str) -> Result<(), BoxError> {
let result =
prepare_preview::prepare_iq3(Path::new(source), Path::new(destination), levels.parse()?)?;
let result = prepare_preview::prepare_iq3(Path::new(source), Path::new(destination), levels.parse()?)?;
print_derived_preview("EXPERIMENTAL IQ3_S-derived F32 KAR-2", destination, &result);
Ok(())
}
fn prepare_mixed(source: &str, destination: &str, levels: &str) -> Result<(), BoxError> {
let result =
prepare_preview::prepare_mixed(Path::new(source), Path::new(destination), levels.parse()?)?;
print_derived_preview(
"EXPERIMENTAL mixed GGUF-derived F32 KAR-2",
destination,
&result,
);
let result = prepare_preview::prepare_mixed(Path::new(source), Path::new(destination), levels.parse()?)?;
print_derived_preview("EXPERIMENTAL mixed GGUF-derived F32 KAR-2", destination, &result);
Ok(())
}
@@ -131,12 +112,7 @@ async fn prepare_sharded(action: &str, rest: &[String]) -> Outcome {
Some(prepare_sharded_streamed(spec, dir, destination, levels).await)
}
("prepare-sharded-streamed", [spec, sf, dir, of, destination, lf, levels, pf, limit])
if flags(&[
(sf, "--source-dir"),
(of, "--output"),
(lf, "--levels"),
(pf, "--ple-part-elements"),
]) =>
if flags(&[(sf, "--source-dir"), (of, "--output"), (lf, "--levels"), (pf, "--ple-part-elements")]) =>
{
Some(prepare_sharded_streamed_ple(spec, dir, destination, levels, limit).await)
}
@@ -151,17 +127,9 @@ async fn prepare_sharded_preview(
levels: &str,
) -> Result<(), BoxError> {
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let result = prepare_preview::prepare_sharded(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
)?;
print_derived_preview(
"EXPERIMENTAL sharded GGUF-derived F32 KAR-2",
destination,
&result,
);
let result =
prepare_preview::prepare_sharded(&manifest, Path::new(source_dir), Path::new(destination), levels.parse()?)?;
print_derived_preview("EXPERIMENTAL sharded GGUF-derived F32 KAR-2", destination, &result);
Ok(())
}
@@ -179,11 +147,7 @@ async fn prepare_sharded_streamed(
levels.parse()?,
)?;
let source_bytes = sharded_source_bytes(&manifest)?;
print_header(
"EXPERIMENTAL streamed sharded GGUF-derived F32 KAR-2",
destination,
&result,
);
print_header("EXPERIMENTAL streamed sharded GGUF-derived F32 KAR-2", destination, &result);
print_streamed_sizes(&result, source_bytes);
print_derived_digest(&result);
print_archive_digest(&result);
@@ -197,14 +161,8 @@ async fn prepare_sharded_streamed(
fn print_streamed_sizes(result: &Preview, source_bytes: u64) {
println!("archive bytes: {}", result.archive.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
result.archive.archive_bytes as f64 / source_bytes as f64
);
println!(
"accounted bits per weight: {:.6}",
result.archive.accounted_bpw
);
println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64);
println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw);
}
async fn prepare_sharded_streamed_ple(
+5 -17
View File
@@ -27,9 +27,7 @@ fn single_commands(action: &str, rest: &[String]) -> Outcome {
Some(extract_tokenizer(path, output))
}
("tokenize", [path, input]) => Some(tokenize(path, input, false)),
("tokenize", [path, input, flag]) if flags(&[(flag, "--special")]) => {
Some(tokenize(path, input, true))
}
("tokenize", [path, input, flag]) if flags(&[(flag, "--special")]) => Some(tokenize(path, input, true)),
("detokenize", [path, ids]) => Some(detokenize(path, ids)),
_ => None,
}
@@ -39,9 +37,7 @@ fn batch_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
("pre-tokenize-batch", []) => Some(pre_tokenize_batch()),
("tokenize-batch", [path, flags_rest @ ..])
if flags_rest.iter().all(|flag| flag == "--special") =>
{
("tokenize-batch", [path, flags_rest @ ..]) if flags_rest.iter().all(|flag| flag == "--special") => {
Some(tokenize_batch(path, !flags_rest.is_empty()))
}
("render-chat", []) => Some(render_chat()),
@@ -75,9 +71,7 @@ fn detokenize(path: &str, ids: &str) -> Result<(), BoxError> {
let ids = if ids.is_empty() {
Vec::new()
} else {
ids.split(',')
.map(str::parse::<u32>)
.collect::<Result<Vec<_>, _>>()?
ids.split(',').map(str::parse::<u32>).collect::<Result<Vec<_>, _>>()?
};
println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?);
Ok(())
@@ -122,10 +116,7 @@ fn request_array<'a>(request: &'a Json, key: &str) -> Option<&'a [Json]> {
/// The template keyword arguments of a chat request.
fn request_kwargs(request: &Json) -> Vec<(&str, Json)> {
match request.get("kwargs") {
Some(Json::Object(fields)) => fields
.iter()
.map(|(k, v)| (k.as_str(), v.clone()))
.collect(),
Some(Json::Object(fields)) => fields.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(),
_ => Vec::new(),
}
}
@@ -138,10 +129,7 @@ fn render_chat() -> Result<(), BoxError> {
let rendered = pinned().render(&ChatInput {
messages: request_array(&request, "messages").unwrap_or(&[]),
tools: request_array(&request, "tools"),
add_generation_prompt: !matches!(
request.get("add_generation_prompt"),
Some(Json::Bool(false))
),
add_generation_prompt: !matches!(request.get("add_generation_prompt"), Some(Json::Bool(false))),
kwargs: request_kwargs(&request),
});
println!(
+4 -18
View File
@@ -65,16 +65,12 @@ fn api_key(args: &[String]) -> Result<(), BoxError> {
async fn config_commands(command: &str, rest: &[String]) -> Outcome {
match (command, rest) {
("provision", [flag, path, defer])
if flags(&[(flag, "--config"), (defer, "--defer-memory-check")]) =>
{
("provision", [flag, path, defer]) if flags(&[(flag, "--config"), (defer, "--defer-memory-check")]) => {
Some(provision_deferred(path).await)
}
("provision", [flag, path]) if flags(&[(flag, "--config")]) => Some(provision(path).await),
("check-config", []) => Some(check_config(None)),
("check-config", [flag, config]) if flags(&[(flag, "--config")]) => {
Some(check_config(Some(Path::new(config))))
}
("check-config", [flag, config]) if flags(&[(flag, "--config")]) => Some(check_config(Some(Path::new(config)))),
_ => None,
}
}
@@ -164,18 +160,8 @@ fn service_unit_arguments(rest: &[String]) -> Result<(&String, &String, Option<&
{
Ok((config, working_dir, None))
}
[
config_flag,
config,
work_flag,
working_dir,
env_flag,
env_file,
] if flags(&[
(config_flag, "--config"),
(work_flag, "--working-dir"),
(env_flag, "--env-file"),
]) =>
[config_flag, config, work_flag, working_dir, env_flag, env_file]
if flags(&[(config_flag, "--config"), (work_flag, "--working-dir"), (env_flag, "--env-file")]) =>
{
Ok((config, working_dir, Some(Path::new(env_file))))
}
+1 -4
View File
@@ -5,10 +5,7 @@ use leleka_control_plane::prepare_preview;
pub(super) fn print_top_tensor_distortions(distortions: &[prepare_preview::TensorDistortion]) {
let mut ranked = distortions.iter().collect::<Vec<_>>();
ranked.sort_by(|a, b| b.relative_l2.total_cmp(&a.relative_l2));
println!(
"highest relative L2 by KAR record (top 20 of {}):",
ranked.len()
);
println!("highest relative L2 by KAR record (top 20 of {}):", ranked.len());
for tensor in ranked.into_iter().take(20) {
println!(
" {:.8} kind={} bytes={} {}",
+1 -1
View File
@@ -47,7 +47,7 @@ pub struct Config {
/// `api_monitor`: keep the last requests' prompts and answers in memory for `GET /api/requests` (off by default).
pub api_monitor: bool,
/// EXPERIMENTAL `tool_call_recovery` (off by default): read a declared tool's call written in a drifted form as the
/// call. See `docs/api-contract.md`, "Tool-call recovery (experimental)".
/// call.
pub tool_call_recovery: bool,
/// The `sampling` block: defaults for what a request leaves out.
pub sampling: leleka_serving_policy::shared::ConfigSampling,
+11 -45
View File
@@ -19,17 +19,13 @@ fn check_entry(file: &ControlVectorFile) -> Result<(), String> {
/// The file read and parsed as a control vector GGUF.
fn read_vector(file: &ControlVectorFile) -> Result<VectorFile, String> {
let metadata = fs::metadata(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
let metadata =
fs::metadata(&file.path).map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if !metadata.is_file() || metadata.len() > 256 * 1024 * 1024 {
return Err(format!(
"control_vector {} must be a regular file of at most 256 MiB",
file.path.display()
));
return Err(format!("control_vector {} must be a regular file of at most 256 MiB", file.path.display()));
}
let parsed = leleka_serving_policy::cvec::parse_gguf(
&fs::read(&file.path)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?,
&fs::read(&file.path).map_err(|error| format!("control_vector {}: {error}", file.path.display()))?,
)
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
if parsed.architecture.as_deref() != Some("controlvector") {
@@ -48,41 +44,23 @@ fn check_direction(
width: &mut Option<u64>,
) -> Result<(), String> {
if tensor.kind != 0 {
return Err(format!(
"control_vector {}: {} must be f32",
file.path.display(),
tensor.name
));
return Err(format!("control_vector {}: {} must be f32", file.path.display(), tensor.name));
}
if *width.get_or_insert(tensor.elements) != tensor.elements {
return Err(format!(
"control_vector {}: direction tensors differ in width",
file.path.display()
));
return Err(format!("control_vector {}: direction tensors differ in width", file.path.display()));
}
Ok(())
}
/// The `direction.<layer>` tensors of a file: at least one, all checked.
fn check_directions(
parsed: &VectorFile,
file: &ControlVectorFile,
width: &mut Option<u64>,
) -> Result<(), String> {
fn check_directions(parsed: &VectorFile, file: &ControlVectorFile, width: &mut Option<u64>) -> Result<(), String> {
let mut found = false;
for tensor in parsed
.tensors
.iter()
.filter(|t| t.name.starts_with("direction."))
{
for tensor in parsed.tensors.iter().filter(|t| t.name.starts_with("direction.")) {
check_direction(tensor, file, width)?;
found = true;
}
if !found {
return Err(format!(
"control_vector {}: no direction.<layer> tensors",
file.path.display()
));
return Err(format!("control_vector {}: no direction.<layer> tensors", file.path.display()));
}
Ok(())
}
@@ -123,24 +101,12 @@ impl ControlVector {
/// The flags that carry the checked files, the mode, the direction layer and the layer range.
fn arguments(&self, list: &[String], mode: Mode) -> Vec<String> {
let mut args = vec!["--control-vector-scaled".to_owned(), list.join(",")];
args.extend([
"--cvec-mode".to_owned(),
if mode == Mode::Project {
"project"
} else {
"add"
}
.to_owned(),
]);
args.extend(["--cvec-mode".to_owned(), if mode == Mode::Project { "project" } else { "add" }.to_owned()]);
if let Some(dir) = &self.dir {
args.extend(["--cvec-dir".to_owned(), dir.clone()]);
}
if let Some([first, last]) = self.layer_range {
args.extend([
"--control-vector-layer-range".to_owned(),
first.to_string(),
last.to_string(),
]);
args.extend(["--control-vector-layer-range".to_owned(), first.to_string(), last.to_string()]);
}
args
}
+1 -1
View File
@@ -4,10 +4,10 @@ use super::{
Config, Duration, FileConfig, FileEngine, FileExtraWorker, OsString, Path, PathBuf, SocketAddr, WorkerConfig, fs,
};
mod config_assembly;
mod load;
mod load_checks;
mod load_engine;
mod config_assembly;
mod load_sections;
mod load_with_path;
mod startup_preparation;
@@ -24,8 +24,7 @@ pub(super) struct Surface {
pub(super) trusted_origins: Vec<String>,
pub(super) sampling: leleka_serving_policy::shared::ConfigSampling,
pub(super) shared_settings_file: Option<PathBuf>,
pub(super) mcp_servers:
std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
pub(super) mcp_servers: std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
pub(super) mcp_settings: crate::mcp::Settings,
}
+31 -114
View File
@@ -5,9 +5,7 @@ use super::config_assembly::{EngineSide, Identity, Surface};
use super::{Config, FileConfig, Path, PathBuf, WorkerConfig, fs};
/// The file named by the CLI path or the environment, parsed, with its asset bundles and native model validated.
pub(super) fn read_checked_file(
path: Option<&Path>,
) -> Result<(Option<PathBuf>, FileConfig), crate::BoxError> {
pub(super) fn read_checked_file(path: Option<&Path>) -> Result<(Option<PathBuf>, FileConfig), crate::BoxError> {
let (config_path, file) = read_file(path)?;
crate::asset_bundle::validate(&file.assets)?;
if let Some(native) = &file.native_model {
@@ -29,30 +27,18 @@ fn read_file(path: Option<&Path>) -> Result<(Option<PathBuf>, FileConfig), crate
Ok((config_path, file))
}
fn owns_native_flag(arg: &str) -> bool {
["--pack", "--native", "--gguf"]
.iter()
.any(|key| arg == *key || arg.starts_with(&format!("{key}=")))
["--pack", "--native", "--gguf"].iter().any(|key| arg == *key || arg.starts_with(&format!("{key}=")))
}
/// `STRATA_TOKENIZER_DIR` or the engine's `tokenizer_dir`, replaced by the native model's when there is one.
fn tokenizer_setting(
file: &FileConfig,
worker: Option<&WorkerConfig>,
) -> Result<Option<PathBuf>, crate::BoxError> {
fn tokenizer_setting(file: &FileConfig, worker: Option<&WorkerConfig>) -> Result<Option<PathBuf>, crate::BoxError> {
let mut tokenizer_dir = crate::env_settings::os_string("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.tokenizer_dir.clone())
});
.or_else(|| file.engine.as_ref().and_then(|engine| engine.tokenizer_dir.clone()));
if let Some(native) = &file.native_model {
let worker = worker.ok_or("native_model requires an engine executable")?;
if tokenizer_dir.is_some() || worker.args.iter().any(|arg| owns_native_flag(arg)) {
return Err(
"native_model owns pack/source/tokenizer settings; remove conflicting overrides"
.into(),
);
return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into());
}
tokenizer_dir = Some(native.output.join("tokenizer"));
}
@@ -60,10 +46,7 @@ fn tokenizer_setting(
}
/// A `runtime` block replaces the engine child: it excludes an engine and the settings the runtime process owns.
fn check_runtime_exclusive(
file: &FileConfig,
worker: Option<&WorkerConfig>,
) -> Result<(), crate::BoxError> {
fn check_runtime_exclusive(file: &FileConfig, worker: Option<&WorkerConfig>) -> Result<(), crate::BoxError> {
if file.runtime.is_none() {
return Ok(());
}
@@ -98,11 +81,7 @@ fn gptoss_setting(
) -> Result<Option<PathBuf>, crate::BoxError> {
let gptoss_gguf = crate::env_settings::os_string("STRATA_GPTOSS_GGUF")
.map(PathBuf::from)
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.gptoss_gguf.clone())
});
.or_else(|| file.engine.as_ref().and_then(|engine| engine.gptoss_gguf.clone()));
if gptoss_gguf.is_some() && file.vision.is_some() {
return Err("vision is not available for the gpt-oss family (gptoss_gguf)".into());
}
@@ -113,10 +92,7 @@ fn gptoss_setting(
}
/// `gpu_requirement`, `cuda_memory` and `engine_probe` all need an engine child.
fn check_host_settings(
file: &FileConfig,
worker: Option<&WorkerConfig>,
) -> Result<(), crate::BoxError> {
fn check_host_settings(file: &FileConfig, worker: Option<&WorkerConfig>) -> Result<(), crate::BoxError> {
if worker.is_none() && file.gpu_requirement.is_some() {
return Err("gpu_requirement requires an engine executable".into());
}
@@ -141,15 +117,8 @@ fn check_mtp_pack(file: &FileConfig, worker: Option<&WorkerConfig>) -> Result<()
if !file.assets.iter().any(|asset| &asset.directory == mtp) {
return Err("mtp_pack must exactly match a pinned assets bundle directory".into());
}
if mtp.to_str().is_none()
|| worker
.args
.iter()
.any(|arg| arg == "--mtp" || arg.starts_with("--mtp="))
{
return Err(
"mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args".into(),
);
if mtp.to_str().is_none() || worker.args.iter().any(|arg| arg == "--mtp" || arg.starts_with("--mtp=")) {
return Err("mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args".into());
}
Ok(())
}
@@ -161,21 +130,14 @@ fn is_name_byte(b: u8) -> bool {
/// `STRATA_MODEL_ID` or the file's `model`: 1..180 ASCII letters, digits, dots, hyphens or underscores.
fn model_id(from_file: Option<String>) -> Result<Option<String>, crate::BoxError> {
let model = crate::env_settings::text("STRATA_MODEL_ID")?.or(from_file);
if model
.as_ref()
.is_some_and(|id| id.is_empty() || id.len() > 180 || !id.bytes().all(is_name_byte))
{
return Err(
"model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores".into(),
);
if model.as_ref().is_some_and(|id| id.is_empty() || id.len() > 180 || !id.bytes().all(is_name_byte)) {
return Err("model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores".into());
}
Ok(model)
}
/// The API key read from `STRATA_API_KEY_FILE` or the file's `api_key_file`.
fn api_key_setting(
from_file: Option<PathBuf>,
) -> Result<Option<std::sync::Arc<crate::auth::ApiKey>>, crate::BoxError> {
fn api_key_setting(from_file: Option<PathBuf>) -> Result<Option<std::sync::Arc<crate::auth::ApiKey>>, crate::BoxError> {
let key = crate::env_settings::os_string("STRATA_API_KEY_FILE")
.map(PathBuf::from)
.or(from_file)
@@ -186,14 +148,11 @@ fn api_key_setting(
/// `STRATA_RESPONSE_HISTORY_DIR` or the file's: absolute, not the root, no `..`.
fn history_dir_setting(from_file: Option<PathBuf>) -> Result<Option<PathBuf>, crate::BoxError> {
let dir = crate::env_settings::os_string("STRATA_RESPONSE_HISTORY_DIR")
.map(PathBuf::from)
.or(from_file);
let dir = crate::env_settings::os_string("STRATA_RESPONSE_HISTORY_DIR").map(PathBuf::from).or(from_file);
if dir.as_ref().is_some_and(|p| {
!p.is_absolute()
|| p.file_name().is_none()
|| p.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
|| p.components().any(|c| matches!(c, std::path::Component::ParentDir))
}) {
return Err("response_history_dir must be an absolute non-root path without '..'".into());
}
@@ -207,13 +166,8 @@ fn aliases_of(file: &FileConfig, model: Option<&str>) -> Result<Vec<String>, cra
Some(value) => leleka_serving_policy::shared::normalize_aliases(value, model.unwrap_or(""))
.map_err(|message| format!("config {message}"))?,
};
if aliases
.iter()
.any(|alias| alias.len() > 180 || !alias.bytes().all(is_name_byte))
{
return Err(
"aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(),
);
if aliases.iter().any(|alias| alias.len() > 180 || !alias.bytes().all(is_name_byte)) {
return Err("aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into());
}
Ok(aliases)
}
@@ -221,11 +175,8 @@ fn aliases_of(file: &FileConfig, model: Option<&str>) -> Result<Vec<String>, cra
/// The browser origins that may call the API, and the trusted ones.
fn read_origins(file: &FileConfig) -> Result<(Vec<String>, Vec<String>), crate::BoxError> {
let null = serde_json::Value::Null;
let cors_origins = leleka_serving_policy::cors::origins_of(
file.cors_origins.as_ref().unwrap_or(&null),
"cors_origins",
true,
)?;
let cors_origins =
leleka_serving_policy::cors::origins_of(file.cors_origins.as_ref().unwrap_or(&null), "cors_origins", true)?;
let trusted_origins = leleka_serving_policy::cors::origins_of(
file.trusted_origins.as_ref().unwrap_or(&null),
"trusted_origins",
@@ -235,13 +186,10 @@ fn read_origins(file: &FileConfig) -> Result<(Vec<String>, Vec<String>), crate::
}
/// The sampling defaults; keys the engine does not know are logged and ignored.
fn read_sampling(
file: &FileConfig,
) -> Result<leleka_serving_policy::shared::ConfigSampling, crate::BoxError> {
fn read_sampling(file: &FileConfig) -> Result<leleka_serving_policy::shared::ConfigSampling, crate::BoxError> {
let null = serde_json::Value::Null;
let sampling = leleka_serving_policy::shared::sampling_defaults_from_config(
file.sampling.as_ref().unwrap_or(&null),
)?;
let sampling =
leleka_serving_policy::shared::sampling_defaults_from_config(file.sampling.as_ref().unwrap_or(&null))?;
for ignored in &sampling.ignored {
crate::elog!("config sampling.{ignored}: unknown key, ignored");
}
@@ -249,10 +197,7 @@ fn read_sampling(
}
/// The vision section needs a non-lazy engine child.
pub(super) fn check_vision(
file: &FileConfig,
worker: Option<&WorkerConfig>,
) -> Result<(), crate::BoxError> {
pub(super) fn check_vision(file: &FileConfig, worker: Option<&WorkerConfig>) -> Result<(), crate::BoxError> {
let Some(vision) = &file.vision else {
return Ok(());
};
@@ -271,10 +216,7 @@ pub(super) fn tool_call_recovery(from_file: Option<bool>) -> Result<bool, crate:
match crate::env_settings::text("STRATA_TOOL_CALL_RECOVERY")?.as_deref() {
Some("1" | "true") => Ok(true),
Some("0" | "false") => Ok(false),
Some(other) => Err(format!(
"STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}"
)
.into()),
Some(other) => Err(format!("STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}").into()),
None => Ok(from_file == Some(true)),
}
}
@@ -286,11 +228,7 @@ fn resolve_runtime(
worker: Option<&WorkerConfig>,
) -> Result<Option<crate::runtime_config::RuntimeBackend>, crate::BoxError> {
check_runtime_exclusive(file, worker)?;
let runtime = file
.runtime
.take()
.map(crate::runtime_config::FileRuntime::resolve)
.transpose()?;
let runtime = file.runtime.take().map(crate::runtime_config::FileRuntime::resolve).transpose()?;
if let Some(runtime) = &runtime {
tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone());
}
@@ -310,11 +248,7 @@ pub(super) fn resolve_engine_side(
let gptoss_gguf = gptoss_setting(file, worker, tokenizer_dir.as_ref())?;
check_host_settings(file, worker)?;
check_mtp_pack(file, worker)?;
Ok(EngineSide {
runtime,
tokenizer_dir,
gptoss_gguf,
})
Ok(EngineSide { runtime, tokenizer_dir, gptoss_gguf })
}
/// The model ID, API key, response history directory and aliases.
@@ -323,41 +257,24 @@ pub(super) fn resolve_identity(file: &mut FileConfig) -> Result<Identity, crate:
let api_key = api_key_setting(file.api_key_file.take())?;
let response_history_dir = history_dir_setting(file.response_history_dir.take())?;
let aliases = aliases_of(file, model.as_deref())?;
Ok(Identity {
model,
api_key,
response_history_dir,
aliases,
})
Ok(Identity { model, api_key, response_history_dir, aliases })
}
/// What clients see: origins, sampling defaults, the thinking budget, shared settings and the MCP servers.
pub(super) fn resolve_surface(
file: &FileConfig,
config_path: Option<&Path>,
) -> Result<Surface, crate::BoxError> {
pub(super) fn resolve_surface(file: &FileConfig, config_path: Option<&Path>) -> Result<Surface, crate::BoxError> {
let (cors_origins, trusted_origins) = read_origins(file)?;
let sampling = read_sampling(file)?;
if let Some(value) = &file.reasoning_budget_tokens {
leleka_serving_policy::reasoning::parse_budget(None, Some(value))
.map_err(|message| format!("config {message}"))?;
}
let shared_settings_file = file
.shared_settings_file
.clone()
.or_else(|| config_path.map(crate::settings::default_shared_path));
let shared_settings_file =
file.shared_settings_file.clone().or_else(|| config_path.map(crate::settings::default_shared_path));
let (mcp_servers, mcp_settings) = Config::read_mcp(
file.mcp_servers.as_ref(),
file.mcp_servers_desktop.as_ref(),
file.mcp_config_file.as_deref(),
file.mcp.as_ref(),
)?;
Ok(Surface {
cors_origins,
trusted_origins,
sampling,
shared_settings_file,
mcp_servers,
mcp_settings,
})
Ok(Surface { cors_origins, trusted_origins, sampling, shared_settings_file, mcp_servers, mcp_settings })
}
+19 -58
View File
@@ -20,13 +20,8 @@ fn args_and_startup_timeout(file: &FileConfig) -> Result<(Vec<String>, u64), cra
let timeout_override = crate::env_settings::number::<u64>("STRATA_STARTUP_TIMEOUT_S")?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
let startup_timeout_s =
timeout_override.or_else(|| file.engine.as_ref().and_then(|engine| engine.startup_timeout_s)).unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
@@ -44,11 +39,8 @@ fn restarts_limit(file: &FileConfig) -> Result<u32, crate::BoxError> {
}
fn generation_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
let generation_timeout_s = crate::env_settings::number::<u64>("STRATA_GENERATION_TIMEOUT_S")?.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
let generation_timeout_s = crate::env_settings::number::<u64>("STRATA_GENERATION_TIMEOUT_S")?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.generation_timeout_s));
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
@@ -61,10 +53,7 @@ fn with_control_vector(
engine_file: Option<&FileEngine>,
) -> Result<Vec<String>, crate::BoxError> {
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
if args
.iter()
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
{
if args.iter().any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-")) {
return Err(concat!(
"control_vector owns the --control-vector*/--cvec-* arguments; ",
"remove them from engine args"
@@ -77,9 +66,7 @@ fn with_control_vector(
}
/// The watchdog and idle settings of the engine block.
fn stall_and_idle(
engine_file: Option<&FileEngine>,
) -> Result<(Option<u64>, Option<f64>), crate::BoxError> {
fn stall_and_idle(engine_file: Option<&FileEngine>) -> Result<(Option<u64>, Option<f64>), crate::BoxError> {
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("stall_timeout_s must be between 1 and 86400".into());
@@ -98,21 +85,10 @@ pub(super) fn read_knobs(file: &FileConfig) -> Result<Knobs, crate::BoxError> {
let engine_file = file.engine.as_ref();
let args = with_control_vector(args, engine_file)?;
let (stall_timeout_s, idle_unload_s) = stall_and_idle(engine_file)?;
Ok(Knobs {
args,
startup_timeout_s,
max_restarts,
generation_timeout_s,
stall_timeout_s,
idle_unload_s,
})
Ok(Knobs { args, startup_timeout_s, max_restarts, generation_timeout_s, stall_timeout_s, idle_unload_s })
}
fn main_worker(
executable: OsString,
engine_file: Option<&FileEngine>,
knobs: Knobs,
) -> WorkerConfig {
fn main_worker(executable: OsString, engine_file: Option<&FileEngine>, knobs: Knobs) -> WorkerConfig {
WorkerConfig {
executable,
cuda_memory: None,
@@ -123,9 +99,7 @@ fn main_worker(
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
stall_timeout: knobs.stall_timeout_s.map(Duration::from_secs),
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
min_free_vram_mib: engine_file
.and_then(|engine| engine.min_free_vram_mib)
.unwrap_or(0),
min_free_vram_mib: engine_file.and_then(|engine| engine.min_free_vram_mib).unwrap_or(0),
vision: None,
}
}
@@ -137,9 +111,7 @@ pub(super) fn build_worker(
knobs: Knobs,
) -> Result<Option<WorkerConfig>, crate::BoxError> {
match executable {
Some(executable) if !executable.is_empty() => {
Ok(Some(main_worker(executable, engine_file, knobs)))
}
Some(executable) if !executable.is_empty() => Ok(Some(main_worker(executable, engine_file, knobs))),
Some(_) => Err("engine executable cannot be empty".into()),
None if !knobs.args.is_empty() => Err("engine args require an executable".into()),
None => Ok(None),
@@ -148,9 +120,11 @@ pub(super) fn build_worker(
/// The pool dispatcher does not load or unload workers on demand.
fn check_pool_loading(file: &FileConfig) -> Result<(), crate::BoxError> {
if file.engine.as_ref().is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
if file
.engine
.as_ref()
.is_some_and(|engine| engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0))
{
return Err(concat!(
"extra_workers cannot be combined with lazy_load or idle_unload_s: ",
"the pool dispatcher does not load or unload workers on demand"
@@ -161,10 +135,7 @@ fn check_pool_loading(file: &FileConfig) -> Result<(), crate::BoxError> {
}
/// A pool needs stdio engines that load on start: no runtime block, no lazy or idle unload, no vision.
fn check_pool_exclusions(
file: &FileConfig,
extra: &[FileExtraWorker],
) -> Result<(), crate::BoxError> {
fn check_pool_exclusions(file: &FileConfig, extra: &[FileExtraWorker]) -> Result<(), crate::BoxError> {
if extra.is_empty() {
return Ok(());
}
@@ -186,10 +157,7 @@ fn check_pool_exclusions(
Ok(())
}
fn extra_worker(
main: Option<&WorkerConfig>,
entry: &FileExtraWorker,
) -> Result<WorkerConfig, crate::BoxError> {
fn extra_worker(main: Option<&WorkerConfig>, entry: &FileExtraWorker) -> Result<WorkerConfig, crate::BoxError> {
let Some(main) = main else {
return Err("extra_workers require an engine executable".into());
};
@@ -216,17 +184,10 @@ pub(super) fn extra_workers(
file: &FileConfig,
main: Option<&WorkerConfig>,
) -> Result<Vec<WorkerConfig>, crate::BoxError> {
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
let extra = file.engine.as_ref().map(|engine| engine.extra_workers.as_slice()).unwrap_or_default();
check_pool_exclusions(file, extra)?;
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
extra
.iter()
.map(|entry| extra_worker(main, entry))
.collect()
extra.iter().map(|entry| extra_worker(main, entry)).collect()
}
@@ -47,8 +47,7 @@ fn prompt_date_setting(file: &FileConfig) -> Result<crate::responses::PromptDate
}
fn queue_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
let queue_timeout_s = crate::env_settings::number::<u64>("STRATA_QUEUE_TIMEOUT_S")?
.or(file.queue_timeout_s);
let queue_timeout_s = crate::env_settings::number::<u64>("STRATA_QUEUE_TIMEOUT_S")?.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
@@ -56,9 +55,8 @@ fn queue_timeout(file: &FileConfig) -> Result<Option<u64>, crate::BoxError> {
}
fn shutdown_grace(file: &FileConfig) -> Result<u64, crate::BoxError> {
let shutdown_grace_s = crate::env_settings::number::<u64>("STRATA_SHUTDOWN_GRACE_S")?
.or(file.shutdown_grace_s)
.unwrap_or(0);
let shutdown_grace_s =
crate::env_settings::number::<u64>("STRATA_SHUTDOWN_GRACE_S")?.or(file.shutdown_grace_s).unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
@@ -68,8 +66,7 @@ fn shutdown_grace(file: &FileConfig) -> Result<u64, crate::BoxError> {
/// The servers of Claude Desktop's file: `mcpServers` (or `mcp_servers`) at the top.
fn servers_of_file(path: &Path) -> Result<Servers, crate::BoxError> {
let location = format!("mcp_config_file {}", path.display());
let text =
std::fs::read_to_string(path).map_err(|error| format!("[strata] {location}: {error}"))?;
let text = std::fs::read_to_string(path).map_err(|error| format!("[strata] {location}: {error}"))?;
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|error| format!("[strata] {location}: {error}"))?;
let block = data
@@ -86,30 +83,17 @@ impl Config {
let prompt_date = prompt_date_setting(file)?;
let queue_timeout_s = queue_timeout(file)?;
let shutdown_grace_s = shutdown_grace(file)?;
Ok(Limits {
bind,
max_in_flight_requests,
prompt_date,
queue_timeout_s,
shutdown_grace_s,
})
Ok(Limits { bind, max_in_flight_requests, prompt_date, queue_timeout_s, shutdown_grace_s })
}
pub(super) fn read_engine(file: &FileConfig) -> Result<EngineSection, crate::BoxError> {
let executable = crate::env_settings::os_string("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let executable = crate::env_settings::os_string("STRATA_ENGINE_EXE")
.or_else(|| file.engine.as_ref().map(|engine| OsString::from(&engine.executable)));
let knobs = engine::read_knobs(file)?;
let idle_unload_s = knobs.idle_unload_s;
let worker = engine::build_worker(executable, file.engine.as_ref(), knobs)?;
let extra_workers = engine::extra_workers(file, worker.as_ref())?;
Ok(EngineSection {
worker,
extra_workers,
idle_unload_s,
})
Ok(EngineSection { worker, extra_workers, idle_unload_s })
}
/// The four MCP entries of the file: `mcp_servers`, `mcpServers`, `mcp_config_file` and the `mcp` settings block.
@@ -121,14 +105,8 @@ impl Config {
) -> Result<Mcp, crate::BoxError> {
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
servers.unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
desktop.unwrap_or(&null),
"config mcpServers",
)?);
mcp_servers.extend(crate::mcp::servers_from(servers.unwrap_or(&null), "config mcp_servers")?);
mcp_servers.extend(crate::mcp::servers_from(desktop.unwrap_or(&null), "config mcpServers")?);
if let Some(path) = config_file {
// Claude Desktop's format; a name in both takes this file's entry.
mcp_servers.extend(servers_of_file(path)?);
@@ -1,7 +1,7 @@
//! `Config::load_with_path`: the file, the environment, and the cross-checks between the sections.
use super::load_checks as check;
use super::config_assembly::CheckedSections;
use super::load_checks as check;
use super::{Config, Path};
impl Config {
@@ -15,13 +15,7 @@ impl Config {
let surface = check::resolve_surface(&file, config_path.as_deref())?;
check::check_vision(&file, engine.worker.as_ref())?;
let tool_call_recovery = check::tool_call_recovery(file.tool_call_recovery)?;
let sections = CheckedSections {
limits,
engine,
side,
identity,
surface,
};
let sections = CheckedSections { limits, engine, side, identity, surface };
Ok(Self::assemble(file, sections, tool_call_recovery))
}
}
@@ -20,9 +20,7 @@ impl Config {
self.prepare_assets().await
}
pub(in super::super) async fn prepare_assets(
&mut self,
) -> Result<(), Box<dyn std::error::Error>> {
pub(in super::super) async fn prepare_assets(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.probe_engine().await?;
// Parse all manifests before any acquisition, including the source model.
if let Some(native) = &self.native_model {
@@ -35,10 +33,7 @@ impl Config {
async fn probe_engine(&self) -> Result<(), Box<dyn std::error::Error>> {
if self.engine_probe {
let worker = self
.worker
.as_ref()
.ok_or("engine_probe requires an engine executable")?;
let worker = self.worker.as_ref().ok_or("engine_probe requires an engine executable")?;
crate::engine_probe::check(&worker.executable).await?;
}
Ok(())
@@ -53,10 +48,7 @@ impl Config {
.as_mut()
.ok_or("mtp_pack requires worker")?
.args
.extend([
"--mtp".to_owned(),
mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(),
]);
.extend(["--mtp".to_owned(), mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned()]);
}
Ok(())
}
@@ -67,16 +59,12 @@ impl Config {
let primary = native.ensure().await?;
let output = native.output.to_str().ok_or("pack path must be UTF-8")?;
let source = primary.to_str().ok_or("source path must be UTF-8")?;
self.worker
.as_mut()
.ok_or("native_model requires worker")?
.args
.extend([
"--pack".to_owned(),
output.to_owned(),
"--native".to_owned(),
source.to_owned(),
]);
self.worker.as_mut().ok_or("native_model requires worker")?.args.extend([
"--pack".to_owned(),
output.to_owned(),
"--native".to_owned(),
source.to_owned(),
]);
}
Ok(())
}
@@ -94,10 +82,7 @@ impl Config {
policy.required_mib,
policy.reserve_mib
);
self.worker
.as_mut()
.ok_or("cuda_memory requires worker")?
.cuda_memory = Some(selected);
self.worker.as_mut().ok_or("cuda_memory requires worker")?.cuda_memory = Some(selected);
}
self.host_checked = true;
}
+24 -113
View File
@@ -24,13 +24,7 @@ fn push_string(bytes: &mut Vec<u8>, text: &[u8]) {
bytes.extend_from_slice(text);
}
fn control_vector_file(
dir: &Path,
name: &str,
architecture: &str,
kind: u32,
elements: u64,
) -> PathBuf {
fn control_vector_file(dir: &Path, name: &str, architecture: &str, kind: u32, elements: u64) -> PathBuf {
let mut bytes = b"GGUF".to_vec();
bytes.extend_from_slice(&3u32.to_le_bytes());
bytes.extend_from_slice(&1u64.to_le_bytes());
@@ -70,10 +64,7 @@ fn assert_serving_worker(worker: WorkerConfig) {
assert!(worker.lazy);
assert_eq!(worker.min_free_vram_mib, 20000);
assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120)));
assert_eq!(
worker.before_load,
Some(crate::worker::BeforeLoad::Shell("echo hook".into()))
);
assert_eq!(worker.before_load, Some(crate::worker::BeforeLoad::Shell("echo hook".into())));
}
#[test]
@@ -87,32 +78,16 @@ fn serving_settings_are_read_and_checked_at_start() {
assert_eq!(config.sampling.sampling.top_k, Some(30));
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
assert_eq!(
config.shared_settings_file,
Some(dir.join("config.shared-settings.json"))
);
assert_eq!(config.shared_settings_file, Some(dir.join("config.shared-settings.json")));
assert_serving_worker(config.worker.unwrap());
let _ = fs::remove_dir_all(dir);
}
#[test]
fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on() {
let dir = temp("tool-call-recovery");
assert!(
!load(&dir, json!({"model": "m"}))
.unwrap()
.tool_call_recovery,
"experimental: opt-in"
);
assert!(
load(&dir, json!({"model": "m", "tool_call_recovery": true}))
.unwrap()
.tool_call_recovery
);
assert!(
!load(&dir, json!({"model": "m", "tool_call_recovery": false}))
.unwrap()
.tool_call_recovery
);
assert!(!load(&dir, json!({"model": "m"})).unwrap().tool_call_recovery, "experimental: opt-in");
assert!(load(&dir, json!({"model": "m", "tool_call_recovery": true})).unwrap().tool_call_recovery);
assert!(!load(&dir, json!({"model": "m", "tool_call_recovery": false})).unwrap().tool_call_recovery);
assert!(load(&dir, json!({"model": "m", "tool_call_recovery": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
@@ -120,16 +95,8 @@ fn tool_call_recovery_is_off_unless_the_config_or_the_environment_turns_it_on()
#[test]
fn the_request_monitor_is_enabled_only_by_a_true_boolean() {
let dir = temp("api-monitor");
assert!(
load(&dir, json!({"model": "m", "api_monitor": true}))
.unwrap()
.api_monitor
);
assert!(
!load(&dir, json!({"model": "m", "api_monitor": false}))
.unwrap()
.api_monitor
);
assert!(load(&dir, json!({"model": "m", "api_monitor": true})).unwrap().api_monitor);
assert!(!load(&dir, json!({"model": "m", "api_monitor": false})).unwrap().api_monitor);
assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err());
let _ = fs::remove_dir_all(dir);
}
@@ -144,14 +111,8 @@ fn bad_serving_settings_stop_the_start() {
("aliases", json!({"aliases": [1]})),
("alias charset", json!({"aliases": ["has space"]})),
("budget", json!({"reasoning_budget_tokens": "many"})),
(
"stall",
json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}),
),
(
"idle",
json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}),
),
("stall", json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}})),
("idle", json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}})),
] {
assert!(load(&dir, value).is_err(), "{name}");
}
@@ -191,20 +152,9 @@ fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() {
assert_runtime_refuses_engine_starters(&dir, &runtime);
// Alone it is accepted up to the credential, which comes from the environment.
let error = load(&dir, json!({"runtime": runtime})).err().unwrap();
assert!(
error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"),
"{error}"
);
let engine_error = load(
&dir,
json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}),
)
.err()
.unwrap();
assert!(
engine_error.contains("mutually exclusive"),
"{engine_error}"
);
assert!(error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"), "{error}");
let engine_error = load(&dir, json!({"runtime": runtime, "engine": {"executable": "/bin/e"}})).err().unwrap();
assert!(engine_error.contains("mutually exclusive"), "{engine_error}");
let _ = fs::remove_dir_all(dir);
}
/// The documented example stays a valid block: it parses completely and stops only at the
@@ -212,8 +162,7 @@ fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() {
#[test]
fn the_runtime_example_config_is_valid_up_to_the_credential() {
let dir = temp("runtime-example");
let example: serde_json::Value =
serde_json::from_str(include_str!("../../config.runtime.example.json")).unwrap();
let example: serde_json::Value = serde_json::from_str(include_str!("../../config.runtime.example.json")).unwrap();
let mut value = example.clone();
value.as_object_mut().unwrap().remove("api_key_file");
let error = load(&dir, value).err().unwrap();
@@ -227,34 +176,17 @@ fn assert_control_vector_arguments(args: &[String], good: &Path) {
assert_eq!(args[3], format!("{}:0.5", good.display()));
assert_eq!(
args[4..],
[
"--cvec-mode",
"project",
"--cvec-dir",
"single:3",
"--control-vector-layer-range",
"2",
"40"
]
["--cvec-mode", "project", "--cvec-dir", "single:3", "--control-vector-layer-range", "2", "40"]
);
}
fn assert_unusable_vector_files_refused(dir: &Path) {
for (name, value) in [
(
"wrong arch",
control_vector_file(dir, "arch.gguf", "llama", 0, 8),
),
(
"f16",
control_vector_file(dir, "f16.gguf", "controlvector", 1, 8),
),
("wrong arch", control_vector_file(dir, "arch.gguf", "llama", 0, 8)),
("f16", control_vector_file(dir, "f16.gguf", "controlvector", 1, 8)),
] {
let vector = json!({"files": [{"path": value, "scale": 1.0}]});
let result = load(
dir,
json!({"engine": {"executable": "/bin/e", "control_vector": vector}}),
);
let result = load(dir, json!({"engine": {"executable": "/bin/e", "control_vector": vector}}));
assert!(result.is_err(), "{name}");
}
}
@@ -303,47 +235,26 @@ fn vision_json() -> serde_json::Value {
}
fn assert_vision_refused(dir: &Path, vision: &serde_json::Value) {
assert!(load(dir, json!({"vision": vision})).err().unwrap().contains("requires an engine"));
assert!(
load(dir, json!({"vision": vision}))
load(dir, json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision}))
.err()
.unwrap()
.contains("requires an engine")
);
assert!(
load(
dir,
json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision})
)
.err()
.unwrap()
.contains("text-only")
);
assert!(
load(
dir,
json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}})
)
.is_err()
.contains("text-only")
);
assert!(load(dir, json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}})).is_err());
}
#[test]
fn vision_section_needs_an_engine_and_is_text_only_when_lazy() {
let dir = temp("vision");
let vision = vision_json();
let config = load(
&dir,
json!({"engine": {"executable": "/bin/true"}, "vision": vision}),
)
.unwrap();
let config = load(&dir, json!({"engine": {"executable": "/bin/true"}, "vision": vision})).unwrap();
let loaded = config.vision.unwrap();
assert!(loaded.gpu);
assert_eq!(loaded.cuda_device, Some(1));
assert_eq!(loaded.max_tokens, Some(1024));
assert!(
config.worker.unwrap().vision.is_none(),
"serve hands the started encoder to the worker"
);
assert!(config.worker.unwrap().vision.is_none(), "serve hands the started encoder to the worker");
assert_vision_refused(&dir, &vision);
let _ = fs::remove_dir_all(dir);
}
+17 -69
View File
@@ -14,9 +14,7 @@ impl Policy {
if self.required_mib == 0 {
return Err("cuda_memory.required_mib must be positive");
}
self.required_mib
.checked_add(self.reserve_mib)
.ok_or("cuda_memory budget overflow")
self.required_mib.checked_add(self.reserve_mib).ok_or("cuda_memory budget overflow")
}
pub async fn select(self) -> Result<Selection, String> {
self.validate()?;
@@ -42,10 +40,7 @@ impl Selection {
pub async fn free_mib(selection: Option<&Selection>) -> Option<u64> {
let devices = inventory().await.ok()?;
match selection {
Some(selection) => devices
.iter()
.find(|d| d.uuid == selection.uuid)
.map(|d| d.free),
Some(selection) => devices.iter().find(|d| d.uuid == selection.uuid).map(|d| d.free),
None => devices.iter().map(|d| d.free).max(),
}
}
@@ -57,13 +52,10 @@ struct Device {
fn uuid_valid(uuid: &str) -> bool {
uuid.len() == 40
&& uuid.starts_with("GPU-")
&& uuid[4..].bytes().enumerate().all(|(i, b)| {
if [8, 13, 18, 23].contains(&i) {
b == b'-'
} else {
b.is_ascii_hexdigit()
}
})
&& uuid[4..]
.bytes()
.enumerate()
.all(|(i, b)| if [8, 13, 18, 23].contains(&i) { b == b'-' } else { b.is_ascii_hexdigit() })
}
fn visibility(value: Option<&str>) -> Result<Option<Vec<String>>, String> {
let Some(value) = value else { return Ok(None) };
@@ -71,8 +63,7 @@ fn visibility(value: Option<&str>) -> Result<Option<Vec<String>>, String> {
return Ok(Some(Vec::new()));
}
let ids: Vec<_> = value.split(',').map(str::to_owned).collect();
if ids.iter().any(|id| !uuid_valid(id)) || ids.iter().collect::<HashSet<_>>().len() != ids.len()
{
if ids.iter().any(|id| !uuid_valid(id)) || ids.iter().collect::<HashSet<_>>().len() != ids.len() {
return Err(concat!(
"cuda_memory requires CUDA_VISIBLE_DEVICES unset or a comma-separated list of full GPU UUIDs; ",
"ordinal, abbreviated and MIG identifiers are unsupported"
@@ -107,21 +98,11 @@ fn parse_line<'a>(line: &'a str, ids: &mut HashSet<&'a str>) -> Result<Device, S
"Enabled" => false,
_ => return Err("unknown GPU MIG mode".into()),
};
Ok(Device {
uuid: v[0].to_owned(),
free,
eligible,
})
Ok(Device { uuid: v[0].to_owned(), free, eligible })
}
fn choose(
policy: Policy,
mut devices: Vec<Device>,
allowed: Option<&[String]>,
) -> Result<Selection, String> {
fn choose(policy: Policy, mut devices: Vec<Device>, allowed: Option<&[String]>) -> Result<Selection, String> {
let needed = policy.validate()?;
devices.retain(|d| {
d.eligible && d.free >= needed && allowed.is_none_or(|ids| ids.contains(&d.uuid))
});
devices.retain(|d| d.eligible && d.free >= needed && allowed.is_none_or(|ids| ids.contains(&d.uuid)));
devices.sort_by(|a, b| b.free.cmp(&a.free).then(a.uuid.cmp(&b.uuid)));
let device = devices.into_iter().next().ok_or_else(|| {
format!(
@@ -132,10 +113,7 @@ fn choose(
needed
)
})?;
Ok(Selection {
uuid: device.uuid,
policy,
})
Ok(Selection { uuid: device.uuid, policy })
}
/// The devices `nvidia-smi` lists: at most 8 KiB of output, a successful exit and valid UTF-8.
async fn read_devices(child: &mut tokio::process::Child) -> Result<Vec<Device>, String> {
@@ -151,12 +129,7 @@ async fn read_devices(child: &mut tokio::process::Child) -> Result<Vec<Device>,
if bytes.len() > 8192 {
return Err("GPU inventory exceeds 8 KiB".to_owned());
}
if !child
.wait()
.await
.map_err(|_| "GPU query wait failed")?
.success()
{
if !child.wait().await.map_err(|_| "GPU query wait failed")?.success() {
return Err("GPU memory query failed".into());
}
parse(std::str::from_utf8(&bytes).map_err(|_| "GPU inventory is not UTF-8")?)
@@ -167,10 +140,7 @@ async fn inventory() -> Result<Vec<Device>, String> {
return Err("cuda_memory requires Linux".into());
}
let mut child = Command::new("nvidia-smi")
.args([
"--query-gpu=uuid,memory.total,memory.free,mig.mode.current",
"--format=csv,noheader,nounits",
])
.args(["--query-gpu=uuid,memory.total,memory.free,mig.mode.current", "--format=csv,noheader,nounits"])
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
@@ -197,18 +167,10 @@ mod tests {
const B: &str = "GPU-00000000-0000-0000-0000-000000000002";
#[test]
fn selection_respects_budget_visibility_and_mig() {
let p = Policy {
required_mib: 7000,
reserve_mib: 1000,
};
let p = Policy { required_mib: 7000, reserve_mib: 1000 };
let data = format!("{A},8192,8000,Disabled\n{B},16384,16000,[N/A]\n");
assert_eq!(choose(p, parse(&data).unwrap(), None).unwrap().uuid, B);
assert_eq!(
choose(p, parse(&data).unwrap(), Some(&[A.into()]))
.unwrap()
.uuid,
A
);
assert_eq!(choose(p, parse(&data).unwrap(), Some(&[A.into()])).unwrap().uuid, A);
assert!(choose(p, parse(&data).unwrap(), Some(&[])).is_err());
assert!(choose(p, parse(&format!("{A},8192,7999,Disabled")).unwrap(), None).is_err());
assert!(choose(p, parse(&format!("{A},8192,8000,Enabled")).unwrap(), None).is_err());
@@ -229,21 +191,7 @@ mod tests {
] {
assert!(parse(&s).is_err());
}
assert!(
Policy {
required_mib: 0,
reserve_mib: 1
}
.validate()
.is_err()
);
assert!(
Policy {
required_mib: u64::MAX,
reserve_mib: 1
}
.validate()
.is_err()
);
assert!(Policy { required_mib: 0, reserve_mib: 1 }.validate().is_err());
assert!(Policy { required_mib: u64::MAX, reserve_mib: 1 }.validate().is_err());
}
}
+15 -54
View File
@@ -60,15 +60,8 @@ pub fn fingerprint(path: &Path) -> Result<Identity, String> {
})
}
fn ensure_unchanged(
source: &File,
path: &Path,
file_size: u64,
gguf_sha256: &[u8; 32],
) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != file_size
|| hash_file(path)? != *gguf_sha256
{
fn ensure_unchanged(source: &File, path: &Path, file_size: u64, gguf_sha256: &[u8; 32]) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != file_size || hash_file(path)? != *gguf_sha256 {
return Err("GGUF source changed during IQ3 derivation".into());
}
Ok(())
@@ -83,33 +76,17 @@ struct Run {
}
/// Checks the tensor is whole IQ3_S blocks and positions `source` at its first byte.
fn seek_to_tensor(
source: &mut File,
data_start: u64,
tensor: &gguf::TensorInfo,
) -> Result<(), String> {
fn seek_to_tensor(source: &mut File, data_start: u64, tensor: &gguf::TensorInfo) -> Result<(), String> {
if !tensor.bytes.is_multiple_of(iq3_s::BLOCK_BYTES as u64) {
return Err(format!(
"{}: IQ3_S tensor is not block-aligned",
tensor.name
));
return Err(format!("{}: IQ3_S tensor is not block-aligned", tensor.name));
}
let absolute = data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
source
.seek(SeekFrom::Start(absolute))
.map_err(|error| error.to_string())?;
let absolute = data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?;
source.seek(SeekFrom::Start(absolute)).map_err(|error| error.to_string())?;
Ok(())
}
impl Run {
fn add_tensor(
&mut self,
source: &mut File,
data_start: u64,
tensor: &gguf::TensorInfo,
) -> Result<(), String> {
fn add_tensor(&mut self, source: &mut File, data_start: u64, tensor: &gguf::TensorInfo) -> Result<(), String> {
seek_to_tensor(source, data_start, tensor)?;
let offset = self.derived_bytes;
let mut iq3_hash = Sha256::new();
@@ -138,27 +115,20 @@ impl Run {
iq3_hash: &mut Sha256,
f32_hash: &mut Sha256,
) -> Result<(), String> {
source
.read_exact(&mut self.block_buffer[..count])
.map_err(|error| error.to_string())?;
source.read_exact(&mut self.block_buffer[..count]).map_err(|error| error.to_string())?;
iq3_hash.update(&self.block_buffer[..count]);
self.hash_blocks(count, f32_hash)?;
let expanded = (count / iq3_s::BLOCK_BYTES)
.checked_mul(iq3_s::BLOCK_ELEMENTS * 4)
.ok_or("derived IQ3 byte count overflow")?;
self.derived_bytes = self
.derived_bytes
.checked_add(expanded as u64)
.ok_or("derived IQ3 byte count overflow")?;
self.derived_bytes =
self.derived_bytes.checked_add(expanded as u64).ok_or("derived IQ3 byte count overflow")?;
Ok(())
}
/// Decode the first `count` buffered bytes and feed the F32 values to the tensor and derived digests.
fn hash_blocks(&mut self, count: usize, f32_hash: &mut Sha256) -> Result<(), String> {
for block in self.block_buffer[..count]
.as_chunks::<{ iq3_s::BLOCK_BYTES }>()
.0
{
for block in self.block_buffer[..count].as_chunks::<{ iq3_s::BLOCK_BYTES }>().0 {
let values = iq3_s::decode_block(block)?;
for value in values {
let bytes = value.to_le_bytes();
@@ -175,9 +145,7 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut digest = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = source
.read(&mut buffer)
.map_err(|error| error.to_string())?;
let count = source.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
@@ -224,14 +192,10 @@ mod tests {
#[test]
fn virtual_f32_identity_uses_tensor_directory_order_and_rejects_bad_source() {
let mut gguf = two_tensor_iq3_gguf();
let path =
std::env::temp_dir().join(format!("strata-iq3-identity-{}.gguf", std::process::id()));
let path = std::env::temp_dir().join(format!("strata-iq3-identity-{}.gguf", std::process::id()));
fs::write(&path, &gguf).unwrap();
let identity = fingerprint(&path).unwrap();
assert_eq!(
identity.gguf_sha256.as_slice(),
Sha256::digest(&gguf).as_slice()
);
assert_eq!(identity.gguf_sha256.as_slice(), Sha256::digest(&gguf).as_slice());
assert_eq!(identity.derived_bytes, 2048);
assert_eq!(identity.tensors[0].name, "second");
assert_eq!(identity.tensors[1].name, "first");
@@ -239,10 +203,7 @@ mod tests {
let mut expected = Sha256::new();
expected.update([2.0f32.to_le_bytes(); 256].concat());
expected.update([1.0f32.to_le_bytes(); 256].concat());
assert_eq!(
identity.derived_sha256.as_slice(),
expected.finalize().as_slice()
);
assert_eq!(identity.derived_sha256.as_slice(), expected.finalize().as_slice());
gguf[0] = b'X';
fs::write(&path, gguf).unwrap();
assert!(fingerprint(&path).is_err());
+8 -30
View File
@@ -58,9 +58,7 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> {
let mut digest = Sha256::new();
let mut buffer = [0u8; 1024 * 1024];
loop {
let count = source
.read(&mut buffer)
.map_err(|error| error.to_string())?;
let count = source.read(&mut buffer).map_err(|error| error.to_string())?;
if count == 0 {
break;
}
@@ -120,12 +118,7 @@ mod tests {
/// The GGUF header of `mixed_gguf`, padded to the 32-byte data alignment.
fn mixed_gguf_header() -> Vec<u8> {
let cases = [
("bf16", 30u32, 192u64, 2u64),
("f32", 0, 128, 2),
("iq3", 21, 0, 256),
("f16", 1, 160, 2),
];
let cases = [("bf16", 30u32, 192u64, 2u64), ("f32", 0, 128, 2), ("iq3", 21, 0, 256), ("f16", 1, 160, 2)];
let mut gguf = b"GGUF".to_vec();
gguf.extend_from_slice(&3u32.to_le_bytes());
gguf.extend_from_slice(&(cases.len() as u64).to_le_bytes());
@@ -161,8 +154,7 @@ mod tests {
let mut iq3 = [0u8; iq3_s::BLOCK_BYTES];
iq3[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
let gguf = mixed_gguf(&iq3);
let path =
std::env::temp_dir().join(format!("strata-mixed-identity-{}.gguf", std::process::id()));
let path = std::env::temp_dir().join(format!("strata-mixed-identity-{}.gguf", std::process::id()));
fs::write(&path, &gguf).unwrap();
let identity = fingerprint(&path).unwrap();
assert_eq!(identity.tensors.len(), 4);
@@ -172,14 +164,8 @@ mod tests {
assert_eq!(identity.tensors[3].derived_offset, 1040);
assert_eq!(identity.derived_bytes, 1048);
let expected = mixed_expected_f32();
assert_eq!(
identity.derived_sha256.as_slice(),
Sha256::digest(&expected).as_slice()
);
assert_eq!(
identity.tensors[2].source_sha256.as_slice(),
Sha256::digest(iq3).as_slice()
);
assert_eq!(identity.derived_sha256.as_slice(), Sha256::digest(&expected).as_slice());
assert_eq!(identity.tensors[2].source_sha256.as_slice(), Sha256::digest(iq3).as_slice());
assert!(crate::derived_iq3::fingerprint(&path).is_err());
fs::remove_file(path).unwrap();
}
@@ -224,16 +210,12 @@ mod tests {
assert_eq!(identity.tensors[1].derived_offset, 128);
assert_eq!(identity.derived_bytes, 1152);
let expected = shard_stream_after(f32_payload);
assert_eq!(
identity.derived_sha256.as_slice(),
Sha256::digest(expected).as_slice()
);
assert_eq!(identity.derived_sha256.as_slice(), Sha256::digest(expected).as_slice());
}
#[test]
fn sharded_identity_sorts_verified_files_and_offsets_tensors() {
let directory =
std::env::temp_dir().join(format!("strata-mixed-shards-{}", std::process::id()));
let directory = std::env::temp_dir().join(format!("strata-mixed-shards-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir(&directory).unwrap();
let (f32_payload, f32, iq3) = write_shard_fixtures(&directory);
@@ -247,11 +229,7 @@ mod tests {
let identity = fingerprint_shards(&manifest, &directory).unwrap();
assert_sharded_identity(&identity, f32_payload);
manifest.files[0].sha256 = "00".repeat(32);
assert!(
fingerprint_shards(&manifest, &directory)
.unwrap_err()
.contains("SHA-256 differs")
);
assert!(fingerprint_shards(&manifest, &directory).unwrap_err().contains("SHA-256 differs"));
fs::remove_dir_all(directory).unwrap();
}
}
+10 -33
View File
@@ -13,14 +13,9 @@ use crate::model::{Manifest, ModelFile};
/// The sharded stream orders GGUF files by byte-wise filename, then tensors
/// by each file's directory order. Every shard is checked against its pinned
/// manifest size and digest before its virtual bytes contribute to the result.
pub fn fingerprint_shards(
manifest: &Manifest,
source_dir: &Path,
) -> Result<ShardedIdentity, String> {
pub fn fingerprint_shards(manifest: &Manifest, source_dir: &Path) -> Result<ShardedIdentity, String> {
if manifest.schema_version != 1 || manifest.files.len() < 2 {
return Err(
"sharded derivation requires a schema v1 manifest with two or more files".into(),
);
return Err("sharded derivation requires a schema v1 manifest with two or more files".into());
}
let mut entries = manifest.files.iter().collect::<Vec<_>>();
entries.sort_unstable_by(|left, right| left.name.as_bytes().cmp(right.name.as_bytes()));
@@ -54,17 +49,12 @@ impl<'a> Shards<'a> {
let bytes = check_shard_file(&path, entry)?;
let identity = fingerprint_inner(&path, Some(&mut self.combined), false)?;
if hex::encode(identity.gguf_sha256) != entry.sha256.to_ascii_lowercase() {
return Err(format!(
"{}: GGUF shard SHA-256 differs from manifest",
entry.name
));
return Err(format!("{}: GGUF shard SHA-256 differs from manifest", entry.name));
}
let tensor_count = identity.tensors.len();
self.append_tensors(identity.tensors)?;
self.derived_bytes = self
.derived_bytes
.checked_add(identity.derived_bytes)
.ok_or("sharded derived byte count overflow")?;
self.derived_bytes =
self.derived_bytes.checked_add(identity.derived_bytes).ok_or("sharded derived byte count overflow")?;
self.shards.push(ShardIdentity {
name: entry.name.clone(),
gguf_sha256: identity.gguf_sha256,
@@ -88,15 +78,10 @@ impl<'a> Shards<'a> {
fn append_tensors(&mut self, tensors: Vec<TensorIdentity>) -> Result<(), String> {
for mut tensor in tensors {
if !self.tensor_names.insert(tensor.name.clone()) {
return Err(format!(
"duplicate tensor across GGUF shards: {}",
tensor.name
));
return Err(format!("duplicate tensor across GGUF shards: {}", tensor.name));
}
tensor.derived_offset = tensor
.derived_offset
.checked_add(self.derived_bytes)
.ok_or("sharded derived offset overflow")?;
tensor.derived_offset =
tensor.derived_offset.checked_add(self.derived_bytes).ok_or("sharded derived offset overflow")?;
self.tensors.push(tensor);
}
Ok(())
@@ -117,20 +102,12 @@ impl<'a> Shards<'a> {
/// Returns the shard byte length after checking it is a regular file of the manifest size.
fn check_shard_file(path: &Path, entry: &ModelFile) -> Result<u64, String> {
if path
.symlink_metadata()
.map_err(|error| error.to_string())?
.file_type()
.is_symlink()
{
if path.symlink_metadata().map_err(|error| error.to_string())?.file_type().is_symlink() {
return Err(format!("{}: GGUF shard is a symlink", entry.name));
}
let bytes = path.metadata().map_err(|error| error.to_string())?.len();
if bytes != entry.size {
return Err(format!(
"{}: GGUF shard size differs from manifest",
entry.name
));
return Err(format!("{}: GGUF shard size differs from manifest", entry.name));
}
Ok(bytes)
}
+18 -51
View File
@@ -16,11 +16,7 @@ pub(super) fn fingerprint_inner(
check_supported(&index.tensors, require_mixed)?;
let gguf_sha256 = hash_file(path)?;
let mut source = File::open(path).map_err(|error| error.to_string())?;
let mut run = Run {
derived: Sha256::new(),
derived_bytes: 0,
tensors: Vec::with_capacity(index.tensors.len()),
};
let mut run = Run { derived: Sha256::new(), derived_bytes: 0, tensors: Vec::with_capacity(index.tensors.len()) };
for tensor in &index.tensors {
run.add_tensor(&mut source, index.summary.data_start, tensor, &mut combined)?;
}
@@ -37,12 +33,7 @@ fn check_supported(tensors: &[gguf::TensorInfo], require_mixed: bool) -> Result<
let has_iq3 = || tensors.iter().any(|tensor| tensor.kind == 21);
let has_other = || tensors.iter().any(|tensor| tensor.kind != 21);
let unsupported = || {
tensors.iter().any(|tensor| {
!matches!(
tensor.kind,
0 | 1 | 8 | 12 | 13 | 14 | 18 | 20 | 21 | 22 | 23 | 30 | 42
)
})
tensors.iter().any(|tensor| !matches!(tensor.kind, 0 | 1 | 8 | 12 | 13 | 14 | 18 | 20 | 21 | 22 | 23 | 30 | 42))
};
if tensors.is_empty() || (require_mixed && (!has_iq3() || !has_other())) || unsupported() {
return Err("mixed derivation requires IQ3_S and supported F32/quantized tensors".into());
@@ -50,15 +41,8 @@ fn check_supported(tensors: &[gguf::TensorInfo], require_mixed: bool) -> Result<
Ok(())
}
fn ensure_unchanged(
source: &File,
path: &Path,
file_size: u64,
gguf_sha256: &[u8; 32],
) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != file_size
|| hash_file(path)? != *gguf_sha256
{
fn ensure_unchanged(source: &File, path: &Path, file_size: u64, gguf_sha256: &[u8; 32]) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != file_size || hash_file(path)? != *gguf_sha256 {
return Err("GGUF source changed during mixed derivation".into());
}
Ok(())
@@ -86,15 +70,11 @@ impl Run {
tensor: &gguf::TensorInfo,
combined: &mut Option<&mut Sha256>,
) -> Result<(), String> {
let absolute = data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
let absolute = data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?;
let offset = self.derived_bytes;
let streamed = self.stream_tensor(source, absolute, tensor, combined)?;
self.derived_bytes = self
.derived_bytes
.checked_add(streamed.bytes)
.ok_or("mixed derived byte count overflow")?;
self.derived_bytes =
self.derived_bytes.checked_add(streamed.bytes).ok_or("mixed derived byte count overflow")?;
check_shape(tensor, streamed.bytes)?;
self.tensors.push(TensorIdentity {
name: tensor.name.clone(),
@@ -117,26 +97,16 @@ impl Run {
) -> Result<Streamed, String> {
let mut source_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let bytes = gguf_f32_stream::visit(
source,
absolute,
tensor.kind,
tensor.bytes,
|raw, f32_bytes| {
source_hash.update(raw);
f32_hash.update(f32_bytes);
self.derived.update(f32_bytes);
if let Some(combined) = combined {
combined.update(f32_bytes);
}
Ok(())
},
)?;
Ok(Streamed {
bytes,
source_sha256: source_hash.finalize().into(),
f32_sha256: f32_hash.finalize().into(),
})
let bytes = gguf_f32_stream::visit(source, absolute, tensor.kind, tensor.bytes, |raw, f32_bytes| {
source_hash.update(raw);
f32_hash.update(f32_bytes);
self.derived.update(f32_bytes);
if let Some(combined) = combined {
combined.update(f32_bytes);
}
Ok(())
})?;
Ok(Streamed { bytes, source_sha256: source_hash.finalize().into(), f32_sha256: f32_hash.finalize().into() })
}
}
@@ -147,10 +117,7 @@ fn check_shape(tensor: &gguf::TensorInfo, tensor_bytes: u64) -> Result<(), Strin
.try_fold(4u64, |product, dim| product.checked_mul(*dim))
.ok_or("mixed derived tensor shape overflow")?;
if tensor_bytes != shape_bytes {
return Err(format!(
"{}: derived tensor size differs from shape",
tensor.name
));
return Err(format!("{}: derived tensor size differs from shape", tensor.name));
}
Ok(())
}
+8 -28
View File
@@ -16,16 +16,10 @@ pub enum GpuRequirement {
struct DriverVersion(u32, u32, u32);
pub async fn report() -> Result<(), crate::BoxError> {
println!(
"platform: {} {}",
std::env::consts::OS,
std::env::consts::ARCH
);
println!("platform: {} {}", std::env::consts::OS, std::env::consts::ARCH);
let version = check(GpuRequirement::Cuda13Linux).await?;
println!("NVIDIA driver: {version}");
println!(
"CUDA 13.0 GA profile driver floor: met (>=580.65.06); GPU/model readiness not checked"
);
println!("CUDA 13.0 GA profile driver floor: met (>=580.65.06); GPU/model readiness not checked");
Ok(())
}
@@ -33,10 +27,7 @@ pub async fn check(_requirement: GpuRequirement) -> Result<String, crate::BoxErr
if !cfg!(target_os = "linux") {
return Err("cuda-13.0-linux requires Linux; select a compatible host/profile".into());
}
let version = match fs::read_to_string("/proc/driver/nvidia/version")
.ok()
.and_then(|s| parse_driver_version(&s))
{
let version = match fs::read_to_string("/proc/driver/nvidia/version").ok().and_then(|s| parse_driver_version(&s)) {
Some(version) => version,
None => probe().await?,
};
@@ -58,9 +49,7 @@ async fn probe() -> Result<DriverVersion, crate::BoxError> {
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(
|_| "NVIDIA driver unavailable; install the host driver and make nvidia-smi accessible",
)?;
.map_err(|_| "NVIDIA driver unavailable; install the host driver and make nvidia-smi accessible")?;
let result = timeout(Duration::from_secs(5), read_probe(&mut child)).await;
match result {
Ok(Ok(version)) => Ok(version),
@@ -129,15 +118,9 @@ mod tests {
#[test]
fn csv_requires_only_versions_and_checks_the_oldest() {
assert_eq!(parse_csv("580.65.06\n600.1.0\n"), Some(MIN_DRIVER));
for invalid in [
"",
"580.65.06\n\n",
"580.65.06\nheader",
"580.65",
"580.65.06.1",
"x580.65.06",
"580.65.06 secret",
] {
for invalid in
["", "580.65.06\n\n", "580.65.06\nheader", "580.65", "580.65.06.1", "x580.65.06", "580.65.06 secret"]
{
assert_eq!(parse_csv(invalid), None, "{invalid:?}");
}
}
@@ -148,10 +131,7 @@ mod tests {
parse_driver_version("NVRM version: NVIDIA UNIX x86_64 Kernel Module 580.65.06 Wed"),
Some(DriverVersion(580, 65, 6))
);
assert_eq!(
parse_driver_version("580.1.0\n"),
Some(DriverVersion(580, 1, 0))
);
assert_eq!(parse_driver_version("580.1.0\n"), Some(DriverVersion(580, 1, 0)));
assert!(DriverVersion(579, 99, 99) < MIN_DRIVER);
assert!(DriverVersion(580, 65, 5) < MIN_DRIVER);
assert!(DriverVersion(580, 65, 6) >= MIN_DRIVER);
+7 -27
View File
@@ -30,10 +30,7 @@ pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, crate::BoxE
return Ok(None);
}
if payload::BYTES.is_empty() {
return Err(
"this binary has no embedded engine; use an external executable or a payload build"
.into(),
);
return Err("this binary has no embedded engine; use an external executable or a payload build".into());
}
materialize(payload::BYTES).map(Some)
}
@@ -41,10 +38,8 @@ pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, crate::BoxE
/// Explicit loader/help probe; this is not an inference or readiness check.
pub fn help() -> Result<(), crate::BoxError> {
let engine = resolve(OsStr::new("@embedded"))?.ok_or("no embedded engine")?;
let status = std::process::Command::new(&engine.executable)
.arg("--help")
.env("CUDA_VISIBLE_DEVICES", "")
.status()?;
let status =
std::process::Command::new(&engine.executable).arg("--help").env("CUDA_VISIBLE_DEVICES", "").status()?;
if !status.success() {
return Err(format!("embedded engine help exited with {status}").into());
}
@@ -75,15 +70,8 @@ fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
return Err(std::io::Error::last_os_error().into());
}
// Use the parent's fd path: CLOEXEC does not need to leak a descriptor to children.
let executable = PathBuf::from(format!(
"/proc/{}/fd/{}",
std::process::id(),
file.as_raw_fd()
));
Ok(EmbeddedEngine {
_file: file,
executable,
})
let executable = PathBuf::from(format!("/proc/{}/fd/{}", std::process::id(), file.as_raw_fd()));
Ok(EmbeddedEngine { _file: file, executable })
}
/// The raw `memfd_create` result (negative on failure, errno set), retrying without `MFD_EXEC` on old kernels.
@@ -91,20 +79,12 @@ fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
fn create_memfd() -> libc::c_int {
// SAFETY: constant NUL-terminated name, supported flags, no borrowed pointers retained.
let fd = unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING | libc::MFD_EXEC,
)
libc::memfd_create(c"strata-engine".as_ptr(), libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING | libc::MFD_EXEC)
};
if fd < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) {
// Older kernels do not know MFD_EXEC. Do not retry EPERM/EACCES policy failures.
// SAFETY: same constant name; legacy flags have been available since Linux 3.17.
return unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
)
};
return unsafe { libc::memfd_create(c"strata-engine".as_ptr(), libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING) };
}
fd
}
+9 -35
View File
@@ -22,11 +22,7 @@ pub fn copy_verified(
digest: &str,
revision: &str,
) -> io::Result<u64> {
let payload = ClaimedPayload {
arch,
digest,
revision,
};
let payload = ClaimedPayload { arch, digest, revision };
copy_with_limit(source, destination, payload, MAX_BYTES)
}
@@ -44,11 +40,7 @@ fn copy_with_limit(
payload: ClaimedPayload<'_>,
limit: u64,
) -> io::Result<u64> {
let ClaimedPayload {
arch,
digest,
revision,
} = payload;
let ClaimedPayload { arch, digest, revision } = payload;
check_provenance(digest, revision)?;
let machine = elf_machine(arch)?;
let header = read_header(&mut source, machine)?;
@@ -73,14 +65,10 @@ fn is_hex_of_length(text: &str, length: usize) -> bool {
fn check_provenance(digest: &str, revision: &str) -> io::Result<()> {
if !is_hex_of_length(digest, 64) {
return Err(invalid(
"embedded engine SHA256 must be 64 hexadecimal characters",
));
return Err(invalid("embedded engine SHA256 must be 64 hexadecimal characters"));
}
if !is_hex_of_length(revision, 40) {
return Err(invalid(
"embedded engine source revision must be a full 40-character Git SHA",
));
return Err(invalid("embedded engine source revision must be a full 40-character Git SHA"));
}
Ok(())
}
@@ -90,9 +78,7 @@ fn elf_machine(arch: &str) -> io::Result<u16> {
match arch {
"x86_64" => Ok(62),
"aarch64" => Ok(183),
_ => Err(invalid(
"embedded engines support Linux x86_64 or aarch64 only",
)),
_ => Err(invalid("embedded engines support Linux x86_64 or aarch64 only")),
}
}
@@ -103,9 +89,7 @@ fn read_header(source: &mut impl Read, machine: u16) -> io::Result<[u8; 64]> {
|| !matches!(u16::from_le_bytes([header[16], header[17]]), 2 | 3)
|| u16::from_le_bytes([header[18], header[19]]) != machine
{
return Err(invalid(
"embedded engine must be an ELF64 little-endian executable for the target architecture",
));
return Err(invalid("embedded engine must be an ELF64 little-endian executable for the target architecture"));
}
Ok(header)
}
@@ -172,15 +156,8 @@ mod tests {
let rev = "a".repeat(40);
let mut output = Vec::new();
let mut input = io::Cursor::new(&elf);
let payload = ClaimedPayload {
arch: "x86_64",
digest: &digest,
revision: &rev,
};
assert_eq!(
copy_with_limit(&mut input, &mut output, payload, elf.len() as u64).unwrap(),
elf.len() as u64
);
let payload = ClaimedPayload { arch: "x86_64", digest: &digest, revision: &rev };
assert_eq!(copy_with_limit(&mut input, &mut output, payload, elf.len() as u64).unwrap(), elf.len() as u64);
assert_eq!(output, elf);
output.clear();
input.set_position(0);
@@ -226,10 +203,7 @@ mod tests {
let source = io::Read::by_ref(&mut input);
assert!(
copy_verified(
InterruptedOnce {
inner: source,
first: &mut interrupted
},
InterruptedOnce { inner: source, first: &mut interrupted },
io::sink(),
"x86_64",
&digest,
+11 -8
View File
@@ -11,17 +11,17 @@ fn spawn_help(executable: &OsStr) -> Result<tokio::process::Child, crate::BoxErr
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "engine loader probe could not start; check executable permissions, ELF architecture and \
loader/shared-library dependencies")?)
.map_err(|_| {
"engine loader probe could not start; check executable permissions, ELF architecture and \
loader/shared-library dependencies"
})?)
}
pub async fn check(executable: &OsStr) -> Result<(), crate::BoxError> {
// Keep the memfd alive until the help process has exited. Serving may have already resolved the payload and keeps
// its own lifetime guard.
let embedded = crate::embedded_engine::resolve(executable)?;
let executable = embedded
.as_ref()
.map_or(executable, |e| e.executable.as_os_str());
let executable = embedded.as_ref().map_or(executable, |e| e.executable.as_os_str());
let mut child = spawn_help(executable)?;
match timeout(Duration::from_secs(10), child.wait()).await {
Ok(Ok(status)) if status.success() => Ok(()),
@@ -33,10 +33,13 @@ pub async fn check(executable: &OsStr) -> Result<(), crate::BoxError> {
failure => {
let _ = child.kill().await;
Err(match failure {
Err(_) => "engine --help probe timed out after 10 seconds; check the selected engine before preparing \
the model",
Err(_) => {
"engine --help probe timed out after 10 seconds; check the selected engine before preparing \
the model"
}
_ => "engine --help probe could not be collected; check the selected engine",
}.into())
}
.into())
}
}
}
+3 -12
View File
@@ -22,11 +22,7 @@
//! * `XDG_CONFIG_HOME`, `HOME`: [`config_home`], where the user systemd unit goes;
//! * every `STRATA_*`: [`strata_variable_names`], scrubbed from the environment of a provisioning child.
use std::{
env::VarError,
ffi::OsString,
path::PathBuf,
};
use std::{env::VarError, ffi::OsString, path::PathBuf};
/// The value of the variable; `Ok(None)` when it is unset, an error when it is set but not valid Unicode.
pub fn text(name: &str) -> Result<Option<String>, VarError> {
@@ -75,9 +71,7 @@ pub fn cuda_visible_devices() -> Result<Option<String>, String> {
pub fn hub_token() -> Result<Option<String>, crate::BoxError> {
match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => Ok(None),
Ok(token) if token.chars().any(char::is_whitespace) => {
Err("HF_TOKEN must not contain whitespace".into())
}
Ok(token) if token.chars().any(char::is_whitespace) => Err("HF_TOKEN must not contain whitespace".into()),
Ok(token) => Ok(Some(token)),
Err(VarError::NotPresent) => Ok(None),
Err(VarError::NotUnicode(_)) => Err("HF_TOKEN must contain valid UTF-8".into()),
@@ -136,8 +130,5 @@ pub fn config_home() -> Result<PathBuf, String> {
/// The names of the variables that start with `STRATA_` (a child that must not inherit the operator's overrides).
pub fn strata_variable_names() -> Vec<OsString> {
std::env::vars_os()
.map(|(name, _)| name)
.filter(|name| name.to_string_lossy().starts_with("STRATA_"))
.collect()
std::env::vars_os().map(|(name, _)| name).filter(|name| name.to_string_lossy().starts_with("STRATA_")).collect()
}
+5 -17
View File
@@ -7,12 +7,7 @@ use crate::gguf;
unsafe extern "C" {
fn strata_ggml_block_bytes(kind: u32) -> u32;
fn strata_ggml_dequantize(
kind: u32,
source: *const u8,
destination: *mut f32,
elements: i64,
) -> c_int;
fn strata_ggml_dequantize(kind: u32, source: *const u8, destination: *mut f32, elements: i64) -> c_int;
}
/// Checks the GGUF reader and the pinned C decoder agree on the kind and that `source` and `destination` are whole,
@@ -46,11 +41,7 @@ fn with_aligned_source<T>(source: &[u8], call: impl FnOnce(*const u8) -> T) -> T
// SAFETY: `aligned` has at least `source.len()` initialized bytes and
// the allocations do not overlap.
unsafe {
std::ptr::copy_nonoverlapping(
source.as_ptr(),
aligned.as_mut_ptr().cast::<u8>(),
source.len(),
);
std::ptr::copy_nonoverlapping(source.as_ptr(), aligned.as_mut_ptr().cast::<u8>(), source.len());
}
aligned.as_ptr().cast::<u8>()
};
@@ -62,13 +53,10 @@ pub fn decode_into(kind: u32, source: &[u8], destination: &mut [f32]) -> Result<
let destination = destination.as_mut_ptr();
// SAFETY: all lengths and alignment are checked above; the C switch calls
// only the pinned ggml function for this kind and fills `destination`.
let status = with_aligned_source(source, |pointer| unsafe {
strata_ggml_dequantize(kind, pointer, destination, elements)
});
let status =
with_aligned_source(source, |pointer| unsafe { strata_ggml_dequantize(kind, pointer, destination, elements) });
if status != 0 {
return Err(format!(
"ggml dequantization does not support GGUF kind {kind}"
));
return Err(format!("ggml dequantization does not support GGUF kind {kind}"));
}
Ok(())
}
@@ -5,10 +5,7 @@ pub(super) fn with_source(len: usize, unaligned: bool, check: impl FnOnce(&mut [
let mut storage = vec![0u8; len + 16];
let start = storage.as_ptr().align_offset(16) + usize::from(unaligned);
let source = &mut storage[start..start + len];
assert_eq!(
source.as_ptr().align_offset(16),
if unaligned { 15 } else { 0 }
);
assert_eq!(source.as_ptr().align_offset(16), if unaligned { 15 } else { 0 });
check(source);
}
@@ -6,13 +6,7 @@ use super::common::{assert_shape_refusals, with_source};
fn pinned_c_table_bytes(name: &str, count: usize, width: usize) -> Vec<u8> {
let source = include_str!("../../../third_party/ggml/ggml-common.h");
let marker = format!(", {name}, {count})");
let body = source
.split_once(&marker)
.unwrap()
.1
.split_once("GGML_TABLE_END()")
.unwrap()
.0;
let body = source.split_once(&marker).unwrap().1.split_once("GGML_TABLE_END()").unwrap().0;
let values: Vec<u64> = body
.split(',')
.map(str::trim)
@@ -26,38 +20,15 @@ fn pinned_c_table_bytes(name: &str, count: usize, width: usize) -> Vec<u8> {
})
.collect();
assert_eq!(values.len(), count);
values
.iter()
.flat_map(|value| value.to_le_bytes()[..width].to_vec())
.collect()
values.iter().flat_map(|value| value.to_le_bytes()[..width].to_vec()).collect()
}
/// (table name, entries, bytes per entry, SHA-256 of the little-endian table bytes) recorded with the port.
const PINNED_TABLES: [(&str, usize, usize, &str); 4] = [
(
"iq2s_grid",
1024,
8,
"e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88",
),
(
"iq3xxs_grid",
256,
4,
"46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d",
),
(
"ksigns_iq2xs",
128,
1,
"a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31",
),
(
"kmask_iq2xs",
8,
1,
"5ac9831b2e30eb285ef34f8501620f878432d5c04331ad1ae47f977a83ba41a5",
),
("iq2s_grid", 1024, 8, "e1aa1473412b0552c2174c30ef22ab4073f6a181b85a17056e8249bd2932fd88"),
("iq3xxs_grid", 256, 4, "46e35f5a997efdee6c99ce57854c8a0d4f0ff8ca57e5e8a60c0793ea580acf5d"),
("ksigns_iq2xs", 128, 1, "a76742a603f8beca5212ecce0f1f02f11a4887fd2f7c8b15aca0ea3eb3380c31"),
("kmask_iq2xs", 8, 1, "5ac9831b2e30eb285ef34f8501620f878432d5c04331ad1ae47f977a83ba41a5"),
];
#[test]
@@ -84,8 +55,7 @@ fn synthetic_iq2s_iq3xxs_block(kind: u32, bits: u16, pattern: usize) -> Vec<u8>
block[34 + group] = (pattern + group * 29) as u8;
}
for subblock in 0..8 {
block[74 + subblock] =
(((pattern + subblock) & 15) | ((((pattern >> 4) + subblock) & 15) << 4)) as u8;
block[74 + subblock] = (((pattern + subblock) & 15) | ((((pattern >> 4) + subblock) & 15) << 4)) as u8;
}
} else {
assert_eq!(kind, 18);
@@ -125,11 +95,7 @@ fn assert_iq2s_iq3xxs_c_bits(kind: u32, source: &[u8], finite: bool) {
if expected.is_nan() {
assert!(actual.is_nan(), "kind {kind} position {position}");
} else {
assert_eq!(
actual.to_bits(),
expected.to_bits(),
"kind {kind} position {position}"
);
assert_eq!(actual.to_bits(), expected.to_bits(), "kind {kind} position {position}");
}
}
}
@@ -142,11 +108,7 @@ fn pinned_ggml_iq2s_iq3xxs_every_finite_fp16_matches_c_bits() {
continue;
}
for kind in [22, 18] {
assert_iq2s_iq3xxs_c_bits(
kind,
&synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)),
true,
);
assert_iq2s_iq3xxs_c_bits(kind, &synthetic_iq2s_iq3xxs_block(kind, bits, usize::from(bits)), true);
}
headers += 1;
}
@@ -176,8 +138,7 @@ impl GridCoverage {
/// Records the grid and sign of one IQ2_S group and returns the sign byte.
fn record_iq2s_group(&mut self, block: &[u8], group: usize) -> u8 {
let grid = usize::from(block[2 + group])
| (usize::from((block[66 + group / 4] >> ((group % 4) * 2)) & 3) << 8);
let grid = usize::from(block[2 + group]) | (usize::from((block[66 + group / 4] >> ((group % 4) * 2)) & 3) << 8);
self.grids[group][grid] = true;
let sign = usize::from(block[34 + group]);
self.signs[group][sign] = true;
@@ -187,11 +148,7 @@ impl GridCoverage {
/// Records the two grids and the sign code of one IQ3_XXS group and returns the sign byte.
fn record_iq3xxs_group(&mut self, block: &[u8], group: usize, c_signs: &[u8]) -> u8 {
let subblock = group / 4;
let word = u32::from_le_bytes(
block[66 + subblock * 4..70 + subblock * 4]
.try_into()
.unwrap(),
);
let word = u32::from_le_bytes(block[66 + subblock * 4..70 + subblock * 4].try_into().unwrap());
let code = ((word >> ((group % 4) * 7)) & 127) as usize;
self.signs[group][code] = true;
self.grids[group * 2][usize::from(block[2 + group * 2])] = true;
@@ -203,11 +160,7 @@ impl GridCoverage {
let code = if kind == 22 {
(block[74 + position / 2] >> ((position % 2) * 4)) & 15
} else {
let word = u32::from_le_bytes(
block[66 + position * 4..70 + position * 4]
.try_into()
.unwrap(),
);
let word = u32::from_le_bytes(block[66 + position * 4..70 + position * 4].try_into().unwrap());
(word >> 28) as u8
};
self.scale[position][usize::from(code)] = true;
@@ -300,29 +253,20 @@ fn check_iq2s_iq3xxs_bulk(kind: u32, edges: &[u16], source: &mut [u8]) {
}
assert_iq2s_iq3xxs_c_bits(kind, source, true);
let outputs = edges.len() * 256;
let cases = [
(0, outputs),
(source.len() - 1, outputs),
(source.len(), outputs - 1),
(source.len(), outputs + 1),
];
assert_shape_refusals(kind, source, &cases, |input, output| {
rust_iq2s_iq3xxs_into(kind, input, output)
});
let cases = [(0, outputs), (source.len() - 1, outputs), (source.len(), outputs - 1), (source.len(), outputs + 1)];
assert_shape_refusals(kind, source, &cases, |input, output| rust_iq2s_iq3xxs_into(kind, input, output));
}
#[test]
fn pinned_ggml_iq2s_iq3xxs_aligned_unaligned_bulk_and_shape_sentinels_match() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800,
0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800, 0xb800, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
];
for kind in [22, 18] {
let bytes = if kind == 22 { 82 } else { 98 };
for unaligned in [false, true] {
with_source(edges.len() * bytes, unaligned, |source| {
check_iq2s_iq3xxs_bulk(kind, &edges, source)
});
with_source(edges.len() * bytes, unaligned, |source| check_iq2s_iq3xxs_bulk(kind, &edges, source));
}
}
}
+7 -23
View File
@@ -5,9 +5,7 @@ use crate::iq3_s;
#[test]
fn pinned_ggml_block_sizes_match_gguf_geometry() {
for kind in [
2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 29, 42,
] {
for kind in [2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 29, 42] {
assert_eq!(
u64::from(unsafe { strata_ggml_block_bytes(kind) }),
gguf::block_geometry(kind).unwrap().1,
@@ -40,13 +38,8 @@ fn synthetic_iq3_block(scale_bits: u16, pattern: u32) -> [u8; iq3_s::BLOCK_BYTES
// For any fixed high byte, odd multiplication, rotation and addition
// form a bijection of all 256 low-byte values at every field position.
let odd = (2 * field + 1) as u8;
let salt = high
.wrapping_mul(0x85eb_ca6b)
.wrapping_add((field as u32).wrapping_mul(0x9e37_79b9));
*byte = low
.wrapping_mul(odd)
.rotate_left((field % 8) as u32)
.wrapping_add((salt ^ (salt >> 16)) as u8);
let salt = high.wrapping_mul(0x85eb_ca6b).wrapping_add((field as u32).wrapping_mul(0x9e37_79b9));
*byte = low.wrapping_mul(odd).rotate_left((field % 8) as u32).wrapping_add((salt ^ (salt >> 16)) as u8);
}
block
}
@@ -138,8 +131,7 @@ fn pinned_ggml_iq3_matches_rust_bits_for_every_finite_fp16_scale() {
#[test]
fn pinned_ggml_iq3_batch_bits_match_rust_with_unaligned_source() {
let scales = [
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
];
let length = scales.len() * iq3_s::BLOCK_BYTES;
let mut storage = vec![0u8; length + 16];
@@ -148,19 +140,14 @@ fn pinned_ggml_iq3_batch_bits_match_rust_with_unaligned_source() {
assert_eq!(source.as_ptr().align_offset(16), 15);
for (number, scale) in scales.into_iter().enumerate() {
let block = synthetic_iq3_block(scale, number as u32 + 70_000);
source[number * iq3_s::BLOCK_BYTES..(number + 1) * iq3_s::BLOCK_BYTES]
.copy_from_slice(&block);
source[number * iq3_s::BLOCK_BYTES..(number + 1) * iq3_s::BLOCK_BYTES].copy_from_slice(&block);
}
let mut reference = vec![0.0f32; scales.len() * iq3_s::BLOCK_ELEMENTS];
let mut actual = vec![0.0f32; reference.len()];
decode_into(21, source, &mut reference).unwrap();
iq3_s::decode_into(source, &mut actual).unwrap();
for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() {
assert_eq!(
actual.to_bits(),
reference.to_bits(),
"batch element={element}"
);
assert_eq!(actual.to_bits(), reference.to_bits(), "batch element={element}");
}
}
@@ -173,10 +160,7 @@ fn independent_rust_iq3_refuses_every_nonfinite_fp16_scale() {
continue;
}
let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits));
assert_eq!(
iq3_s::decode_block(&block).unwrap_err(),
"IQ3_S block has a non-finite scale"
);
assert_eq!(iq3_s::decode_block(&block).unwrap_err(), "IQ3_S block has a non-finite scale");
assert!(iq3_s::decode_into(&block, &mut [0.0; iq3_s::BLOCK_ELEMENTS]).is_err());
rejected += 1;
}
+4 -14
View File
@@ -55,10 +55,7 @@ fn assert_iq4_finite_bits(block: &[u8; 18], scale_bits: u16) {
#[test]
fn pinned_ggml_iq4_matches_rust_bits_for_every_finite_fp16_scale() {
let mut coverage = Iq4Coverage {
packed_fields: [[false; 256]; 16],
codepoints: [[false; 16]; 32],
};
let mut coverage = Iq4Coverage { packed_fields: [[false; 256]; 16], codepoints: [[false; 16]; 32] };
let mut compared = 0;
for scale_bits in 0..=u16::MAX {
if scale_bits & 0x7c00 == 0x7c00 {
@@ -78,8 +75,7 @@ fn pinned_ggml_iq4_matches_rust_bits_for_every_finite_fp16_scale() {
fn pinned_ggml_iq4_batch_bits_match_rust_with_unaligned_source() {
use leleka_quant_core::iq4_nl;
let scales = [
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
];
let length = scales.len() * iq4_nl::BLOCK_BYTES;
let mut storage = vec![0u8; length + 16];
@@ -95,11 +91,7 @@ fn pinned_ggml_iq4_batch_bits_match_rust_with_unaligned_source() {
decode_into(20, source, &mut reference).unwrap();
iq4_nl::decode_into(source, &mut actual).unwrap();
for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() {
assert_eq!(
actual.to_bits(),
reference.to_bits(),
"IQ4_NL batch element={element}"
);
assert_eq!(actual.to_bits(), reference.to_bits(), "IQ4_NL batch element={element}");
}
}
@@ -112,9 +104,7 @@ fn assert_iq4_nonfinite_block(scale_bits: u16) {
decode_into(20, &block, &mut reference).unwrap();
iq4_nl::decode_into(&block, &mut actual).unwrap();
let single = iq4_nl::decode_block(&block).unwrap();
for (element, ((actual, single), reference)) in
actual.iter().zip(&single).zip(&reference).enumerate()
{
for (element, ((actual, single), reference)) in actual.iter().zip(&single).zip(&reference).enumerate() {
if scale_bits & 0x03ff == 0 {
assert!(actual.is_infinite() && reference.is_infinite());
assert_eq!(actual.to_bits(), reference.to_bits());
+14 -47
View File
@@ -46,16 +46,9 @@ fn assert_k_c_reference(kind: u32, block: &[u8], finite: bool) -> [f32; 256] {
assert!(actual.is_finite() && reference.is_finite());
}
if reference.is_nan() {
assert!(
actual.is_nan(),
"kind={kind} element={element} block={block:?}"
);
assert!(actual.is_nan(), "kind={kind} element={element} block={block:?}");
} else {
assert_eq!(
actual.to_bits(),
reference.to_bits(),
"kind={kind} element={element} block={block:?}"
);
assert_eq!(actual.to_bits(), reference.to_bits(), "kind={kind} element={element} block={block:?}");
}
}
actual
@@ -70,11 +63,7 @@ fn pinned_ggml_q4_q5_k_exhaust_each_finite_fp16_scale_role_separately() {
if bits & 0x7c00 == 0x7c00 {
continue;
}
let (d, dmin) = if vary_min {
(0xbc00, bits)
} else {
(bits, 0x3800)
};
let (d, dmin) = if vary_min { (0xbc00, bits) } else { (bits, 0x3800) };
let block = synthetic_k_block(kind, d, dmin, u32::from(bits));
assert_k_c_reference(kind, &block, true);
compared += 1;
@@ -162,11 +151,7 @@ impl KCoverage {
assert!(self.minima.iter().flatten().all(|seen| *seen));
assert!(self.packed_quants.iter().flatten().all(|seen| *seen));
let limit = if kind == 12 { 16 } else { 32 };
assert!(
self.codes
.iter()
.all(|position| position[..limit].iter().all(|seen| *seen))
);
assert!(self.codes.iter().all(|position| position[..limit].iter().all(|seen| *seen)));
if kind == 13 {
assert!(self.high_bytes.iter().flatten().all(|seen| *seen));
}
@@ -190,8 +175,8 @@ fn pinned_ggml_q4_q5_k_packed_fields_and_subscale_positions_match_rust_bits() {
#[test]
fn pinned_ggml_q4_q5_k_joint_finite_edges_and_exact_cancellation_match_rust_bits() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800,
0xb800, 0x3bff, 0xbbff, 0x3c00, 0xbc00, 0x3c01, 0xbc01, 0x7bff, 0xfbff,
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800, 0xb800, 0x3bff,
0xbbff, 0x3c00, 0xbc00, 0x3c01, 0xbc01, 0x7bff, 0xfbff,
];
for kind in [12, 13] {
for (left, d) in edges.into_iter().enumerate() {
@@ -222,11 +207,7 @@ fn check_nonfinite_role(kind: u32, vary_min: bool) {
if bits & 0x7c00 != 0x7c00 {
continue;
}
let (d, dmin) = if vary_min {
(0x3c00, bits)
} else {
(bits, 0xbc00)
};
let (d, dmin) = if vary_min { (0x3c00, bits) } else { (bits, 0xbc00) };
let mut block = synthetic_k_block(kind, d, dmin, u32::from(bits));
assert_k_c_reference(kind, &block, false);
// Explicit all-zero packed scale/minimum/quant values exercise
@@ -240,9 +221,7 @@ fn check_nonfinite_role(kind: u32, vary_min: bool) {
#[test]
fn pinned_ggml_q4_q5_k_nonfinite_scale_roles_and_joint_edges_preserve_c_values() {
let special = [
0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
];
let special = [0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00];
for kind in [12, 13] {
for vary_min in [false, true] {
check_nonfinite_role(kind, vary_min);
@@ -259,11 +238,7 @@ fn pinned_ggml_q4_q5_k_nonfinite_scale_roles_and_joint_edges_preserve_c_values()
/// The Rust decoder of `kind` (Q4_K or Q5_K).
fn rust_k_decode(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> {
use leleka_quant_core::{q4_k, q5_k};
if kind == 12 {
q4_k::decode_into(source, output)
} else {
q5_k::decode_into(source, output)
}
if kind == 12 { q4_k::decode_into(source, output) } else { q5_k::decode_into(source, output) }
}
/// Decodes `edges.len()` blocks of edge scales in `source` with both decoders and checks the shape refusals.
@@ -281,28 +256,20 @@ fn check_k_bulk(kind: u32, edges: &[u16], source: &mut [u8]) {
for (actual, reference) in actual.iter().zip(&reference) {
assert_eq!(actual.to_bits(), reference.to_bits());
}
let cases = [
(source.len() - 1, actual.len()),
(source.len(), actual.len() - 1),
(source.len(), actual.len() + 1),
];
assert_shape_refusals(kind, source, &cases, |input, output| {
rust_k_decode(kind, input, output)
});
let cases = [(source.len() - 1, actual.len()), (source.len(), actual.len() - 1), (source.len(), actual.len() + 1)];
assert_shape_refusals(kind, source, &cases, |input, output| rust_k_decode(kind, input, output));
}
#[test]
fn pinned_ggml_q4_q5_k_aligned_unaligned_bulk_and_shape_contracts_match_rust() {
use leleka_quant_core::{q4_k, q5_k};
let edges = [
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800,
0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800, 0xb800, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
];
for (kind, block_bytes) in [(12, q4_k::BLOCK_BYTES), (13, q5_k::BLOCK_BYTES)] {
for unaligned in [false, true] {
with_source(edges.len() * block_bytes, unaligned, |source| {
check_k_bulk(kind, &edges, source)
});
with_source(edges.len() * block_bytes, unaligned, |source| check_k_bulk(kind, &edges, source));
}
}
}
+8 -28
View File
@@ -69,11 +69,7 @@ fn assert_q6_q2_c_bits(kind: u32, source: &[u8], finite: bool) {
if expected.is_nan() {
assert!(actual.is_nan(), "kind {kind} position {position}");
} else {
assert_eq!(
actual.to_bits(),
expected.to_bits(),
"kind {kind} position {position}"
);
assert_eq!(actual.to_bits(), expected.to_bits(), "kind {kind} position {position}");
}
}
}
@@ -113,10 +109,7 @@ fn pinned_ggml_q6_signed_subscale_quant_pairs_cover_every_output_position() {
}
}
for (position, seen) in pairs.iter().enumerate() {
assert!(
seen.iter().all(|value| *value),
"half/quadrant/lane position {position}"
);
assert!(seen.iter().all(|value| *value), "half/quadrant/lane position {position}");
}
}
@@ -165,11 +158,7 @@ fn pinned_ggml_q6_q2_raw_fields_cover_all_bytes_and_q2_consecutive_codes() {
assert!(raw_seen.iter().all(|seen| seen.iter().all(|value| *value)));
if kind == 42 {
assert_eq!(elements, 64);
assert!(
codes_seen
.iter()
.all(|seen| seen.iter().all(|value| *value))
);
assert!(codes_seen.iter().all(|seen| seen.iter().all(|value| *value)));
}
}
}
@@ -208,29 +197,20 @@ fn check_q6_q2_bulk(kind: u32, edges: &[u16], source: &mut [u8]) {
}
assert_q6_q2_c_bits(kind, source, true);
let outputs = edges.len() * elements as usize;
let cases = [
(0, outputs),
(source.len() - 1, outputs),
(source.len(), outputs - 1),
(source.len(), outputs + 1),
];
assert_shape_refusals(kind, source, &cases, |input, output| {
rust_q6_q2_into(kind, input, output)
});
let cases = [(0, outputs), (source.len() - 1, outputs), (source.len(), outputs - 1), (source.len(), outputs + 1)];
assert_shape_refusals(kind, source, &cases, |input, output| rust_q6_q2_into(kind, input, output));
}
#[test]
fn pinned_ggml_q6_q2_aligned_unaligned_bulk_and_shape_sentinels_match() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800,
0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3800, 0xb800, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
];
for kind in [14, 42] {
let bytes = gguf::block_geometry(kind).unwrap().1 as usize;
for unaligned in [false, true] {
with_source(edges.len() * bytes, unaligned, |source| {
check_q6_q2_bulk(kind, &edges, source)
});
with_source(edges.len() * bytes, unaligned, |source| check_q6_q2_bulk(kind, &edges, source));
}
}
}
+10 -21
View File
@@ -51,11 +51,7 @@ fn assert_q8_finite_bits(scale: u16, position_codes: &mut [[bool; 256]; 32]) {
assert!(scale_codes.into_iter().all(|seen| seen));
for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() {
assert!(actual.is_finite() && reference.is_finite());
assert_eq!(
actual.to_bits(),
reference.to_bits(),
"Q8_0 scale={scale:#06x} element={element}"
);
assert_eq!(actual.to_bits(), reference.to_bits(), "Q8_0 scale={scale:#06x} element={element}");
}
}
@@ -167,11 +163,7 @@ fn assert_iq4xs_finite_bits(block: &[u8; 136], scale: u16, group: usize) {
let actual = iq4_xs::decode_block(block).unwrap();
for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() {
assert!(actual.is_finite() && reference.is_finite());
assert_eq!(
actual.to_bits(),
reference.to_bits(),
"IQ4_XS scale={scale:#06x} group={group} element={element}"
);
assert_eq!(actual.to_bits(), reference.to_bits(), "IQ4_XS scale={scale:#06x} group={group} element={element}");
}
}
@@ -206,8 +198,8 @@ fn pinned_ggml_iq4xs_matches_rust_bits_for_every_finite_scale_subscale_and_codep
fn note_zero_subscales(block: &[u8; 136], zero_positions: &mut [bool; 8]) {
let high = u16::from_le_bytes([block[2], block[3]]);
for (subblock, zero) in zero_positions.iter_mut().enumerate() {
let six = ((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15)
| (((high >> (2 * subblock)) & 3) as u8) << 4;
let six =
((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) | (((high >> (2 * subblock)) & 3) as u8) << 4;
*zero |= six == 32;
}
}
@@ -285,16 +277,13 @@ fn check_unaligned_batch(kind: u32, source: &mut [u8], scales: &[u16], elements:
#[test]
fn pinned_ggml_q8_and_iq4xs_unaligned_batches_match_rust_bits() {
use leleka_quant_core::{iq4_xs, q8_0};
for (kind, block_bytes, elements) in [
(8, q8_0::BLOCK_BYTES, q8_0::BLOCK_ELEMENTS),
(23, iq4_xs::BLOCK_BYTES, iq4_xs::BLOCK_ELEMENTS),
] {
for (kind, block_bytes, elements) in
[(8, q8_0::BLOCK_BYTES, q8_0::BLOCK_ELEMENTS), (23, iq4_xs::BLOCK_BYTES, iq4_xs::BLOCK_ELEMENTS)]
{
let scales = [
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00,
0xbc00, 0x7bff, 0xfbff,
0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, 0xbc00, 0x7bff,
0xfbff,
];
with_source(scales.len() * block_bytes, true, |source| {
check_unaligned_batch(kind, source, &scales, elements)
});
with_source(scales.len() * block_bytes, true, |source| check_unaligned_batch(kind, source, &scales, elements));
}
}
+10 -33
View File
@@ -82,15 +82,13 @@ struct Geometry {
}
fn checked_geometry(source_kind: u32, source_bytes: u64) -> Result<Geometry, String> {
let (block_elements, block_bytes) = gguf::block_geometry(source_kind)
.ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?;
let (block_elements, block_bytes) =
gguf::block_geometry(source_kind).ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?;
let rust = RUST_GEOMETRY.iter().find(|entry| entry.0 == source_kind);
if let Some(&(_, elements, bytes, format)) = rust
&& (block_elements != elements as u64 || block_bytes != bytes as u64)
{
return Err(format!(
"{format} decoder geometry differs from GGUF source kind {source_kind}"
));
return Err(format!("{format} decoder geometry differs from GGUF source kind {source_kind}"));
}
let block_bytes = usize::try_from(block_bytes).map_err(|_| "GGUF block is too large")?;
if block_bytes > SOURCE_CHUNK_BYTES {
@@ -99,10 +97,7 @@ fn checked_geometry(source_kind: u32, source_bytes: u64) -> Result<Geometry, Str
if source_bytes == 0 || !source_bytes.is_multiple_of(block_bytes as u64) {
return Err("GGUF source tensor is empty or not block-aligned".into());
}
Ok(Geometry {
elements: block_elements,
bytes: block_bytes,
})
Ok(Geometry { elements: block_elements, bytes: block_bytes })
}
/// Reusable buffers of the chunk loop.
@@ -112,12 +107,7 @@ struct Scratch {
}
/// Fills `scratch.derived` with the F32 bytes of a non-F32 source chunk.
fn derive_chunk(
source_kind: u32,
geometry: &Geometry,
source: &[u8],
scratch: &mut Scratch,
) -> Result<(), String> {
fn derive_chunk(source_kind: u32, geometry: &Geometry, source: &[u8], scratch: &mut Scratch) -> Result<(), String> {
match source_kind {
1 | 30 => {
for pair in source.as_chunks::<2>().0 {
@@ -167,10 +157,7 @@ impl Decoder {
Ok(Self {
source_kind,
geometry: checked_geometry(source_kind, source_bytes)?,
scratch: Scratch {
derived: Vec::with_capacity(512 * 1024),
decoded: Vec::new(),
},
scratch: Scratch { derived: Vec::with_capacity(512 * 1024), decoded: Vec::new() },
})
}
@@ -190,14 +177,8 @@ impl Decoder {
}
}
fn read_chunk<R: Read>(
reader: &mut R,
raw: &mut AlignedSource,
count: usize,
) -> Result<(), String> {
reader
.read_exact(&mut raw.0[..count])
.map_err(|error| error.to_string())
fn read_chunk<R: Read>(reader: &mut R, raw: &mut AlignedSource, count: usize) -> Result<(), String> {
reader.read_exact(&mut raw.0[..count]).map_err(|error| error.to_string())
}
pub fn visit<R, F>(
@@ -212,9 +193,7 @@ where
F: FnMut(&[u8], &[u8]) -> Result<(), String>,
{
let mut decoder = Decoder::new(source_kind, source_bytes)?;
reader
.seek(SeekFrom::Start(absolute_offset))
.map_err(|error| error.to_string())?;
reader.seek(SeekFrom::Start(absolute_offset)).map_err(|error| error.to_string())?;
let mut raw = Box::new(AlignedSource([0u8; SOURCE_CHUNK_BYTES]));
let chunk_bytes = SOURCE_CHUNK_BYTES / decoder.geometry.bytes * decoder.geometry.bytes;
let mut remaining = source_bytes;
@@ -223,9 +202,7 @@ where
let count = remaining.min(chunk_bytes as u64) as usize;
read_chunk(reader, &mut raw, count)?;
let output_count = decoder.emit(&raw.0[..count], &mut callback)?;
derived_bytes = derived_bytes
.checked_add(output_count as u64)
.ok_or("GGUF derived F32 byte count overflow")?;
derived_bytes = derived_bytes.checked_add(output_count as u64).ok_or("GGUF derived F32 byte count overflow")?;
remaining -= count as u64;
}
Ok(derived_bytes)
@@ -4,9 +4,7 @@ use super::super::*;
use std::io::Cursor;
/// Half-precision bit patterns that exercise subnormals, signs and the largest finite value.
pub(super) const EDGE_HALVES: [u16; 8] = [
0x0000, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
pub(super) const EDGE_HALVES: [u16; 8] = [0x0000, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff];
/// Bytes in front of the tensor in the test file.
pub(super) const PREFIX: usize = 11;
@@ -33,14 +31,7 @@ impl Stream {
source.extend_from_slice(&fill(kind, number, bytes));
}
source.extend_from_slice(&[0x5a; 19]);
Self {
kind,
elements,
bytes,
per_chunk,
blocks,
source,
}
Self { kind, elements, bytes, per_chunk, blocks, source }
}
pub fn requested(&self) -> usize {
@@ -55,10 +46,7 @@ impl Stream {
/// The reference decoder's little-endian F32 bytes of `raw`.
fn oracle_bytes(kind: u32, raw: &[u8], elements: usize) -> Vec<u8> {
let oracle = oracle_floats(kind, raw, elements);
oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
oracle.iter().flat_map(|value| value.to_le_bytes()).collect()
}
/// What the full-stream callback has seen so far: the bytes consumed and the size of each chunk.
@@ -71,19 +59,9 @@ struct Seen {
impl Seen {
/// One chunk is bounded, equals the file bytes at its offset and decodes like the C oracle.
fn check_chunk(&mut self, stream: &Stream, raw: &[u8], derived: &[u8]) {
let Stream {
kind,
elements,
bytes,
per_chunk,
source,
..
} = stream;
let Stream { kind, elements, bytes, per_chunk, source, .. } = stream;
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[PREFIX + self.consumed..PREFIX + self.consumed + raw.len()]
);
assert_eq!(raw, &source[PREFIX + self.consumed..PREFIX + self.consumed + raw.len()]);
let expected = oracle_bytes(*kind, raw, raw.len() / bytes * *elements as usize);
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= stream.derived_bytes(*per_chunk));
@@ -93,10 +71,7 @@ impl Seen {
/// The two chunks have the expected sizes and together cover the requested bytes.
fn check_totals(&self, stream: &Stream) {
let full = (
stream.per_chunk * stream.bytes,
stream.derived_bytes(stream.per_chunk),
);
let full = (stream.per_chunk * stream.bytes, stream.derived_bytes(stream.per_chunk));
let tail = (17 * stream.bytes, stream.derived_bytes(17));
assert_eq!(self.chunks, [full, tail]);
assert_eq!(self.consumed, stream.requested());
@@ -110,16 +85,10 @@ pub(super) fn check_full_stream(stream: &Stream) {
let mut seen = Seen::default();
let requested = stream.requested() as u64;
let kind = stream.kind;
let receipt = visit(
&mut cursor,
PREFIX as u64,
kind,
requested,
|raw, derived| {
seen.check_chunk(stream, raw, derived);
Ok(())
},
)
let receipt = visit(&mut cursor, PREFIX as u64, kind, requested, |raw, derived| {
seen.check_chunk(stream, raw, derived);
Ok(())
})
.unwrap();
seen.check_totals(stream);
assert_eq!(receipt, stream.blocks as u64 * stream.elements * 4);
@@ -132,16 +101,10 @@ fn check_malformed_lengths(stream: &Stream) {
let mut cursor = Cursor::new(&stream.source);
cursor.set_position(7);
let mut calls = 0;
let result = visit(
&mut cursor,
PREFIX as u64,
stream.kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
},
);
let result = visit(&mut cursor, PREFIX as u64, stream.kind, malformed as u64, |_, _| {
calls += 1;
Ok(())
});
assert!(result.is_err());
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
@@ -150,9 +113,7 @@ fn check_malformed_lengths(stream: &Stream) {
/// A source one byte short of the next block is refused; a chunk is delivered only when it was complete.
fn check_truncated_sources(stream: &Stream) {
let Stream {
bytes, per_chunk, ..
} = *stream;
let Stream { bytes, per_chunk, .. } = *stream;
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
@@ -179,37 +140,20 @@ fn check_callback_aborts(stream: &Stream) {
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&stream.source);
let mut calls = 0;
let error = visit(
&mut cursor,
PREFIX as u64,
stream.kind,
stream.requested() as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
let error = visit(&mut cursor, PREFIX as u64, stream.kind, stream.requested() as u64, |_, _| {
calls += 1;
if calls == fail_on { Err("owned callback abort".into()) } else { Ok(()) }
})
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
let read = if fail_on == 1 {
stream.per_chunk * stream.bytes
} else {
stream.requested()
};
let read = if fail_on == 1 { stream.per_chunk * stream.bytes } else { stream.requested() };
assert_eq!(cursor.position(), (PREFIX + read) as u64);
}
}
/// The bounded-chunk contract of the C-parity streams: chunks, offsets, receipts and the failure semantics.
pub(super) fn check_bounded_c_stream_contract(
kinds: [u32; 2],
fill: impl Fn(u32, usize, usize) -> Vec<u8>,
) {
pub(super) fn check_bounded_c_stream_contract(kinds: [u32; 2], fill: impl Fn(u32, usize, usize) -> Vec<u8>) {
for kind in kinds {
let stream = Stream::new(kind, &fill);
check_full_stream(&stream);
@@ -33,9 +33,7 @@ fn header_block(bytes: usize, bits: u16, zero_fields: bool) -> Vec<u8> {
fn iq2s_iq3xxs_streams_preserve_nonfinite_signed_zero_and_zero_packed_fields() {
for kind in [22, 18] {
let bytes = crate::gguf::block_geometry(kind).unwrap().1 as usize;
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for bits in [0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
for zero_fields in [false, true] {
check_block_matches_oracle(kind, &header_block(bytes, bits, zero_fields));
}
@@ -13,13 +13,7 @@ fn iq3_stream_spans_chunks_with_bounded_buffers() {
let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4);
assert!(
decoded
.as_chunks::<4>()
.0
.iter()
.all(|v| *v == 1f32.to_le_bytes())
);
assert!(decoded.as_chunks::<4>().0.iter().all(|v| *v == 1f32.to_le_bytes()));
chunks.push((raw.len(), decoded.len()));
Ok(())
})
@@ -49,10 +43,7 @@ fn iq4_edge_source(blocks: usize, prefix: usize) -> Vec<u8> {
fn iq4_reference_bytes(raw: &[u8]) -> Vec<u8> {
let mut reference = vec![0.0; raw.len() / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
reference
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
reference.iter().flat_map(|value| value.to_le_bytes()).collect()
}
/// The stream delivers one full chunk and then the 257 remaining blocks.
@@ -60,10 +51,7 @@ fn assert_iq4_chunk_shapes(chunks: &[(usize, usize)], blocks_per_chunk: usize) {
assert_eq!(
chunks,
[
(
blocks_per_chunk * iq4_nl::BLOCK_BYTES,
blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4
),
(blocks_per_chunk * iq4_nl::BLOCK_BYTES, blocks_per_chunk * iq4_nl::BLOCK_ELEMENTS * 4),
(257 * iq4_nl::BLOCK_BYTES, 257 * iq4_nl::BLOCK_ELEMENTS * 4),
]
);
@@ -88,19 +76,13 @@ fn iq4_stream_spans_chunks_with_exact_c_parity_and_source_offsets() {
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let output_bytes = visit(
&mut cursor,
prefix as u64,
20,
source_bytes as u64,
|raw, derived| {
let expected_raw = &source[prefix + consumed..prefix + consumed + raw.len()];
assert_iq4_chunk(raw, derived, expected_raw, blocks_per_chunk);
consumed += raw.len();
chunks.push((raw.len(), derived.len()));
Ok(())
},
)
let output_bytes = visit(&mut cursor, prefix as u64, 20, source_bytes as u64, |raw, derived| {
let expected_raw = &source[prefix + consumed..prefix + consumed + raw.len()];
assert_iq4_chunk(raw, derived, expected_raw, blocks_per_chunk);
consumed += raw.len();
chunks.push((raw.len(), derived.len()));
Ok(())
})
.unwrap();
assert_iq4_chunk_shapes(&chunks, blocks_per_chunk);
assert_eq!(consumed, source_bytes);
@@ -128,10 +110,7 @@ fn iq4_stream_refuses_invalid_shapes_before_seek_or_callback() {
#[test]
fn iq4_stream_truncation_never_delivers_an_incomplete_chunk() {
let chunk_bytes = SOURCE_CHUNK_BYTES / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_BYTES;
for available in [
iq4_nl::BLOCK_BYTES - 1,
chunk_bytes + iq4_nl::BLOCK_BYTES - 1,
] {
for available in [iq4_nl::BLOCK_BYTES - 1, chunk_bytes + iq4_nl::BLOCK_BYTES - 1] {
assert_truncated_iq4_is_refused(available, chunk_bytes);
}
}
@@ -145,11 +124,7 @@ fn iq4_stream_callback_failure_stops_without_reading_the_next_chunk() {
let error = visit(&mut cursor, 0, 20, (chunk_bytes * 3) as u64, |raw, _| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
if calls == fail_on {
Err("owned callback failure".into())
} else {
Ok(())
}
if calls == fail_on { Err("owned callback failure".into()) } else { Ok(()) }
})
.unwrap_err();
assert_eq!(error, "owned callback failure");
@@ -184,17 +159,11 @@ fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() {
let mut reference = [0.0; iq4_nl::BLOCK_ELEMENTS];
ggml_bridge::decode_into(20, raw, &mut reference).unwrap();
let mut calls = 0;
let count = visit(
&mut Cursor::new(raw),
0,
20,
iq4_nl::BLOCK_BYTES as u64,
|_, derived| {
calls += 1;
assert_iq4_words_match(derived, reference);
Ok(())
},
)
let count = visit(&mut Cursor::new(raw), 0, 20, iq4_nl::BLOCK_BYTES as u64, |_, derived| {
calls += 1;
assert_iq4_words_match(derived, reference);
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(count, (iq4_nl::BLOCK_ELEMENTS * 4) as u64);
@@ -204,41 +173,19 @@ fn iq4_stream_preserves_existing_nonfinite_classification_and_infinity_signs() {
/// A source one byte short of the 257 blocks it declares is refused.
fn assert_truncated_iq3_source_is_refused(mut source: Vec<u8>) {
source.pop();
assert!(
visit(
&mut Cursor::new(source),
0,
21,
(257 * 110 - 1) as u64,
|_, _| Ok(())
)
.is_err()
);
assert!(visit(&mut Cursor::new(source), 0, 21, (257 * 110 - 1) as u64, |_, _| Ok(())).is_err());
}
/// Asking for one block more than `available` bytes holds fails; a full chunk is delivered only if it was complete.
fn assert_truncated_iq4_is_refused(available: usize, chunk_bytes: usize) {
let requested = if available < chunk_bytes {
iq4_nl::BLOCK_BYTES
} else {
chunk_bytes + iq4_nl::BLOCK_BYTES
};
let requested = if available < chunk_bytes { iq4_nl::BLOCK_BYTES } else { chunk_bytes + iq4_nl::BLOCK_BYTES };
let mut calls = 0;
let result = visit(
&mut Cursor::new(vec![0u8; available]),
0,
20,
requested as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
assert_eq!(
derived.len(),
chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4
);
Ok(())
},
);
let result = visit(&mut Cursor::new(vec![0u8; available]), 0, 20, requested as u64, |raw, derived| {
calls += 1;
assert_eq!(raw.len(), chunk_bytes);
assert_eq!(derived.len(), chunk_bytes / iq4_nl::BLOCK_BYTES * iq4_nl::BLOCK_ELEMENTS * 4);
Ok(())
});
assert!(result.is_err());
assert_eq!(calls, usize::from(available >= chunk_bytes));
}
@@ -33,18 +33,13 @@ fn scale_role_block(bytes: usize, d: u16, dmin: u16, zero_fields: bool) -> Vec<u
#[test]
fn q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() {
let scales = [
0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
];
let scales = [0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00];
for kind in [12, 13] {
let bytes = crate::gguf::block_geometry(kind).unwrap().1 as usize;
for d in scales {
for dmin in scales {
for zero_fields in [false, true] {
check_block_matches_oracle(
kind,
&scale_role_block(bytes, d, dmin, zero_fields),
);
check_block_matches_oracle(kind, &scale_role_block(bytes, d, dmin, zero_fields));
}
}
}
@@ -9,8 +9,7 @@ fn edge_block(kind: u32, number: usize, bytes: usize) -> Vec<u8> {
*byte = (number * 17 + position * 29) as u8;
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2]
.copy_from_slice(&EDGE_HALVES[number % EDGE_HALVES.len()].to_le_bytes());
block[header..header + 2].copy_from_slice(&EDGE_HALVES[number % EDGE_HALVES.len()].to_le_bytes());
block
}
@@ -38,9 +37,7 @@ fn vary_packed_fields(kind: u32, variant: usize, block: &mut [u8]) {
fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() {
for kind in [14, 42] {
let bytes = crate::gguf::block_geometry(kind).unwrap().1;
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for bits in [0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
for variant in 0..3 {
let mut block = vec![0u8; bytes as usize];
for (position, byte) in block.iter_mut().enumerate() {
@@ -18,16 +18,11 @@ fn scaled_block(_kind: u32, number: usize, bytes: usize) -> Vec<u8> {
/// A size one byte short of the tensor is refused before any chunk is delivered.
fn check_short_size_refused(stream: &Stream) {
let mut calls = 0;
let result = visit(
&mut Cursor::new(&stream.source),
PREFIX as u64,
stream.kind,
stream.requested() as u64 - 1,
|_, _| {
let result =
visit(&mut Cursor::new(&stream.source), PREFIX as u64, stream.kind, stream.requested() as u64 - 1, |_, _| {
calls += 1;
Ok(())
},
);
});
assert!(result.is_err());
assert_eq!(calls, 0);
}
@@ -36,16 +31,10 @@ fn check_short_size_refused(stream: &Stream) {
fn check_short_source_refused(stream: &Stream) {
let mut calls = 0;
let mut truncated = Cursor::new(&stream.source[..PREFIX + stream.bytes - 1]);
let result = visit(
&mut truncated,
PREFIX as u64,
stream.kind,
stream.bytes as u64,
|_, _| {
calls += 1;
Ok(())
},
);
let result = visit(&mut truncated, PREFIX as u64, stream.kind, stream.bytes as u64, |_, _| {
calls += 1;
Ok(())
});
assert!(result.is_err());
assert_eq!(calls, 0);
}
@@ -54,22 +43,13 @@ fn check_short_source_refused(stream: &Stream) {
fn check_first_chunk_abort(stream: &Stream) {
let mut calls = 0;
let mut cursor = Cursor::new(&stream.source);
let result = visit(
&mut cursor,
PREFIX as u64,
stream.kind,
stream.requested() as u64,
|_, _| {
calls += 1;
Err("owned callback abort".into())
},
);
let result = visit(&mut cursor, PREFIX as u64, stream.kind, stream.requested() as u64, |_, _| {
calls += 1;
Err("owned callback abort".into())
});
assert_eq!(result.unwrap_err(), "owned callback abort");
assert_eq!(calls, 1);
assert_eq!(
cursor.position(),
(PREFIX + stream.per_chunk * stream.bytes) as u64
);
assert_eq!(cursor.position(), (PREFIX + stream.per_chunk * stream.bytes) as u64);
}
#[test]
@@ -112,13 +92,6 @@ fn actual_target_quant_types_decode_one_block_each() {
.unwrap();
assert_eq!(count, elements * 4, "kind {kind}");
assert_eq!(output.len() as u64, elements * 4, "kind {kind}");
assert!(
output
.as_chunks::<4>()
.0
.iter()
.all(|word| f32::from_le_bytes(*word).is_finite()),
"kind {kind}"
);
assert!(output.as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_finite()), "kind {kind}");
}
}
+11 -54
View File
@@ -22,16 +22,8 @@ const MIN_GAP: Duration = Duration::from_millis(900);
const MIB: f64 = 1_048_576.0;
/// The series the Monitor charts, in the Python service's names.
pub const SERIES: [&str; 8] = [
"gpu_util",
"gpu_mem_used",
"gpu_temp",
"gpu_power",
"cpu",
"ram_used",
"tok_s",
"prefill_tok_s_mean",
];
pub const SERIES: [&str; 8] =
["gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "cpu", "ram_used", "tok_s", "prefill_tok_s_mean"];
fn number(value: &Value) -> Option<f64> {
value.as_f64().filter(|v| v.is_finite())
@@ -59,10 +51,7 @@ pub fn hardware_now(document: &Value) -> Value {
let cpu = &document["cpu"];
if cpu.is_object() {
now.insert("cpu".into(), cpu["system_busy_pct"].clone());
now.insert(
"cpu_process_cores".into(),
cpu["process_busy_cores"].clone(),
);
now.insert("cpu_process_cores".into(), cpu["process_busy_cores"].clone());
}
if document["throughput"].is_object() {
insert_throughput(&mut now, document);
@@ -90,29 +79,16 @@ fn insert_ram(now: &mut Map<String, Value>, ram: &Value) {
now.insert("ram_used".into(), used);
now.insert("ram_total".into(), bytes(&ram["total_mib"]));
now.insert("ram_process_rss".into(), bytes(&ram["process_rss_mib"]));
now.insert(
"ram_process_pinned".into(),
bytes(&ram["process_pinned_mib"]),
);
now.insert("ram_process_pinned".into(), bytes(&ram["process_pinned_mib"]));
now.insert("swap_used".into(), bytes(&ram["swap_used_mib"]));
}
fn insert_throughput(now: &mut Map<String, Value>, document: &Value) {
let throughput = &document["throughput"];
let decoding = document["phase"] == "decode";
now.insert(
"tok_s".into(),
if decoding {
throughput["decode_tok_s_live"].clone()
} else {
json!(0.0)
},
);
now.insert("tok_s".into(), if decoding { throughput["decode_tok_s_live"].clone() } else { json!(0.0) });
now.insert("tok_s_mean".into(), throughput["decode_tok_s_avg"].clone());
now.insert(
"prefill_tok_s_mean".into(),
throughput["prefill_tok_s_avg"].clone(),
);
now.insert("prefill_tok_s_mean".into(), throughput["prefill_tok_s_avg"].clone());
}
/// `hardware_static`: what does not change while the engine runs.
@@ -148,10 +124,7 @@ impl Series {
return;
};
let at = self.clock.now();
if inner
.last
.is_some_and(|last| at.duration_since(last) < MIN_GAP)
{
if inner.last.is_some_and(|last| at.duration_since(last) < MIN_GAP) {
return;
}
inner.last = Some(at);
@@ -170,10 +143,7 @@ impl Series {
};
let mut out = Map::new();
for (key, row) in &inner.rows {
out.insert(
(*key).to_owned(),
Value::Array(row.iter().cloned().collect()),
);
out.insert((*key).to_owned(), Value::Array(row.iter().cloned().collect()));
}
Value::Object(out)
}
@@ -210,10 +180,7 @@ mod tests {
assert_eq!(now["prefill_tok_s_mean"], 5050.0);
let fixed = hardware_static(&document("decode"));
assert_eq!(fixed["gpu_name"], "NVIDIA GeForce RTX 5090");
assert_eq!(
(fixed["gpu_count"].clone(), fixed["threads"].clone()),
(json!(1), json!(32))
);
assert_eq!((fixed["gpu_count"].clone(), fixed["threads"].clone()), (json!(1), json!(32)));
}
#[test]
@@ -249,19 +216,9 @@ mod tests {
fn assert_every_series_is_bounded(snapshot: &Value) {
for key in SERIES {
assert_eq!(
snapshot[key].as_array().unwrap().len(),
HISTORY_SAMPLES,
"{key}"
);
assert_eq!(snapshot[key].as_array().unwrap().len(), HISTORY_SAMPLES, "{key}");
}
// a series the engine did not report is null, not zero
assert!(
snapshot["gpu_temp"]
.as_array()
.unwrap()
.iter()
.all(|v| v == 61)
);
assert!(snapshot["gpu_temp"].as_array().unwrap().iter().all(|v| v == 61));
}
}
+5 -17
View File
@@ -23,35 +23,23 @@ pub struct GptOssCodec {
impl GptOssCodec {
pub fn new(bpe: GgufBpe) -> Result<Self, String> {
let terminal: Vec<u32> = TERMINAL_MARKERS
.iter()
.filter_map(|marker| bpe.token_id(marker))
.collect();
let terminal: Vec<u32> = TERMINAL_MARKERS.iter().filter_map(|marker| bpe.token_id(marker)).collect();
if terminal.is_empty() {
return Err("the vocabulary has no end-of-generation token".into());
}
let markers = SENTINELS
.iter()
.map(|(character, marker)| {
bpe.token_id(marker)
.map(|id| (*character, id))
.ok_or_else(|| format!("the vocabulary lacks {marker}"))
bpe.token_id(marker).map(|id| (*character, id)).ok_or_else(|| format!("the vocabulary lacks {marker}"))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
bpe: Arc::new(bpe),
terminal,
markers,
})
Ok(Self { bpe: Arc::new(bpe), terminal, markers })
}
/// Read the tokenizer from the vocabulary stored in a GGUF file.
pub fn from_gguf(path: &Path) -> Result<Self, String> {
let size = std::fs::metadata(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?
.len();
let file = std::fs::File::open(path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
let size = std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?.len();
let file = std::fs::File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
let gguf = leleka_gguf::Gguf::read(std::io::BufReader::with_capacity(1 << 20, file), size)
.map_err(|e| format!("invalid GGUF {}: {e}", path.display()))?;
Self::new(GgufBpe::from_gguf(&gguf).map_err(|e| e.to_string())?)
+11 -48
View File
@@ -153,10 +153,7 @@ fn a_preamble_and_two_calls_keep_their_order() {
#[test]
fn reasoning_only_closes_the_block_when_its_message_ended() {
let c = codec();
let ended = script(
&c,
&["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"],
);
let ended = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm", "<|end|>"]);
assert_eq!(decode(&c, &ended), "Hmm</think>\n\n");
// cut off in the middle of the reasoning (length limit): no closing marker
let cut = script(&c, &["<|channel|>", "analysis", "<|message|>", "Hmm"]);
@@ -165,29 +162,9 @@ fn reasoning_only_closes_the_block_when_its_message_ended() {
/// Tool calls whose arguments are not a JSON object with identifier keys, as token scripts.
const INVALID_TOOL_CALLS: [&[&str]; 3] = [
&[
"<|channel|>",
"commentary to=functions.f ",
"<|constrain|>",
"json",
"<|message|>",
"{not json",
"<|end|>",
],
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"[1]",
"<|end|>",
],
&[
"<|channel|>",
"commentary to=functions.f ",
"<|message|>",
"{\"a b\":1}",
"<|end|>",
],
&["<|channel|>", "commentary to=functions.f ", "<|constrain|>", "json", "<|message|>", "{not json", "<|end|>"],
&["<|channel|>", "commentary to=functions.f ", "<|message|>", "[1]", "<|end|>"],
&["<|channel|>", "commentary to=functions.f ", "<|message|>", "{\"a b\":1}", "<|end|>"],
];
#[test]
@@ -202,10 +179,7 @@ fn invalid_tool_arguments_are_an_error_when_the_call_ends() {
#[test]
fn multibyte_text_survives_token_boundaries() {
let c = codec();
let ids = script(
&c,
&["<|channel|>", "final", "<|message|>", "héllo 😀 日本"],
);
let ids = script(&c, &["<|channel|>", "final", "<|message|>", "héllo 😀 日本"]);
assert_eq!(decode(&c, &ids), "</think>\n\nhéllo 😀 日本");
}
@@ -222,16 +196,10 @@ fn only_the_renderers_sentinels_become_special_tokens() {
// marker text typed by a client stays ordinary tokens, with or without special parsing
for parse in [true, false] {
let ids = c.encode("<|end|><|start|>", parse).unwrap();
assert!(
!ids.contains(&start) && !ids.contains(&end),
"parse={parse}"
);
assert!(!ids.contains(&start) && !ids.contains(&end), "parse={parse}");
}
// a prompt without sentinels round-trips as plain text
assert_eq!(
c.bpe.decode(&c.encode("plain text", true).unwrap()),
"plain text"
);
assert_eq!(c.bpe.decode(&c.encode("plain text", true).unwrap()), "plain text");
}
#[test]
@@ -249,15 +217,10 @@ fn gptoss_reasons_whatever_the_effort_and_has_no_live_reading() {
use leleka_gateway_domain::output::LivePlan;
use leleka_gateway_domain::responses::{CreateRequest, reasoning_enabled};
let c = codec();
let request: CreateRequest = serde_json::from_value(
serde_json::json!({"model": "m", "input": "x", "reasoning": {"effort": "none"}}),
)
.unwrap();
let request: CreateRequest =
serde_json::from_value(serde_json::json!({"model": "m", "input": "x", "reasoning": {"effort": "none"}}))
.unwrap();
assert!(reasoning_enabled(&request, &c));
let plan = LivePlan {
tools: None,
recovery: false,
keep_raw: false,
};
let plan = LivePlan { tools: None, recovery: false, keep_raw: false };
assert!(c.live_decoder(plan).is_none());
}
+17 -55
View File
@@ -23,22 +23,16 @@ impl Store {
let directory = prepare_directory(directory)?;
let lock = lock_directory(&directory)?;
let store = Self {
directory_handle: File::open(&directory)
.map_err(|_| "cannot open history directory")?,
directory_handle: File::open(&directory).map_err(|_| "cannot open history directory")?,
directory,
_lock: lock,
failed: AtomicBool::new(false),
};
store.clean_stage()?;
// Persist creation of the private directory before acknowledging any data.
File::open(
store
.directory
.parent()
.ok_or("history directory has no parent")?,
)
.and_then(|f| f.sync_all())
.map_err(|_| "cannot flush history parent directory")?;
File::open(store.directory.parent().ok_or("history directory has no parent")?)
.and_then(|f| f.sync_all())
.map_err(|_| "cannot flush history parent directory")?;
Ok(store)
}
@@ -70,18 +64,11 @@ impl Store {
Ok(_) => (),
}
let file = open_private(&path)?;
if file
.metadata()
.map_err(|_| "cannot inspect history snapshot")?
.len()
> MAX_SNAPSHOT_BYTES
{
if file.metadata().map_err(|_| "cannot inspect history snapshot")?.len() > MAX_SNAPSHOT_BYTES {
return Err("history snapshot exceeds size limit");
}
let mut bytes = Vec::new();
file.take(MAX_SNAPSHOT_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|_| "cannot read history snapshot")?;
file.take(MAX_SNAPSHOT_BYTES + 1).read_to_end(&mut bytes).map_err(|_| "cannot read history snapshot")?;
if bytes.len() as u64 > MAX_SNAPSHOT_BYTES {
return Err("history snapshot exceeds size limit");
}
@@ -123,12 +110,8 @@ impl Store {
#[cfg(unix)]
fn check_directory_identity(&self) -> Result<(), &'static str> {
use std::os::unix::fs::MetadataExt;
let current =
fs::symlink_metadata(&self.directory).map_err(|_| "history directory disappeared")?;
let original = self
.directory_handle
.metadata()
.map_err(|_| "cannot inspect history directory")?;
let current = fs::symlink_metadata(&self.directory).map_err(|_| "history directory disappeared")?;
let original = self.directory_handle.metadata().map_err(|_| "cannot inspect history directory")?;
if current.dev() != original.dev()
|| current.ino() != original.ino()
|| !current.is_dir()
@@ -141,13 +124,7 @@ impl Store {
}
/// Writes and syncs the staged snapshot, renames it over `path` and syncs the directory.
fn write_stage(
&self,
file: &mut File,
bytes: &[u8],
stage: &Path,
path: &Path,
) -> Result<(), &'static str> {
fn write_stage(&self, file: &mut File, bytes: &[u8], stage: &Path, path: &Path) -> Result<(), &'static str> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@@ -155,9 +132,7 @@ impl Store {
.map_err(|_| "cannot set private history snapshot permissions")?;
private_file(file)?;
}
file.write_all(bytes)
.and_then(|_| file.sync_all())
.map_err(|_| "cannot flush response history snapshot")?;
file.write_all(bytes).and_then(|_| file.sync_all()).map_err(|_| "cannot flush response history snapshot")?;
fs::rename(stage, path).map_err(|_| "cannot publish response history snapshot")?;
self.directory_handle
.sync_all()
@@ -174,9 +149,7 @@ fn create_stage(stage: &Path) -> Result<File, &'static str> {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
options
.open(stage)
.map_err(|_| "cannot stage response history snapshot")
options.open(stage).map_err(|_| "cannot stage response history snapshot")
}
/// Creates (if absent) and validates the private history directory; returns its canonical path.
@@ -193,8 +166,7 @@ fn prepare_directory(directory: &Path) -> Result<PathBuf, &'static str> {
return Err("cannot create private response history directory; parent must exist");
}
}
let metadata =
fs::symlink_metadata(directory).map_err(|_| "cannot inspect history directory")?;
let metadata = fs::symlink_metadata(directory).map_err(|_| "cannot inspect history directory")?;
if !metadata.is_dir()
|| metadata.file_type().is_symlink()
|| metadata.uid() != unsafe { libc::geteuid() }
@@ -202,9 +174,7 @@ fn prepare_directory(directory: &Path) -> Result<PathBuf, &'static str> {
{
return Err("history directory must be owned by this user with mode 0700, not a symlink");
}
directory
.canonicalize()
.map_err(|_| "cannot resolve history directory")
directory.canonicalize().map_err(|_| "cannot resolve history directory")
}
#[cfg(unix)]
@@ -220,8 +190,7 @@ fn lock_directory(directory: &Path) -> Result<File, &'static str> {
.open(directory.join("history.lock"))
.map_err(|_| "cannot open history lock")?;
private_file(&lock)?;
lock.try_lock()
.map_err(|_| "response history is already in use or cannot be locked")?;
lock.try_lock().map_err(|_| "response history is already in use or cannot be locked")?;
Ok(lock)
}
@@ -229,14 +198,9 @@ fn lock_directory(directory: &Path) -> Result<File, &'static str> {
fn private_file(file: &File) -> Result<(), &'static str> {
use std::os::unix::fs::MetadataExt;
let meta = file.metadata().map_err(|_| "cannot inspect history file")?;
if !meta.is_file()
|| meta.uid() != unsafe { libc::geteuid() }
|| meta.mode() & 0o777 != 0o600
|| meta.nlink() != 1
if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } || meta.mode() & 0o777 != 0o600 || meta.nlink() != 1
{
return Err(
"history files must be private owned regular files with mode 0600 and one link",
);
return Err("history files must be private owned regular files with mode 0600 and one link");
}
Ok(())
}
@@ -249,9 +213,7 @@ fn open_private(path: &Path) -> Result<File, &'static str> {
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = options
.open(path)
.map_err(|_| "cannot open private history file")?;
let file = options.open(path).map_err(|_| "cannot open private history file")?;
#[cfg(unix)]
private_file(&file)?;
Ok(file)
+12 -47
View File
@@ -7,11 +7,7 @@ pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
use std::{ffi::CString, os::unix::ffi::OsStrExt};
let source = CString::new(source.as_os_str().as_bytes())?;
let destination = CString::new(destination.as_os_str().as_bytes())?;
if rename_no_replace(&source, &destination) == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
if rename_no_replace(&source, &destination) == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
#[cfg(target_os = "linux")]
@@ -40,14 +36,10 @@ fn rename_no_replace(source: &std::ffi::CStr, destination: &std::ffi::CStr) -> l
#[cfg(target_os = "windows")]
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
use std::os::windows::ffi::OsStrExt;
let wide =
|path: &Path| -> Vec<u16> { path.as_os_str().encode_wide().chain(Some(0)).collect() };
let wide = |path: &Path| -> Vec<u16> { path.as_os_str().encode_wide().chain(Some(0)).collect() };
let (from, to) = (wide(source), wide(destination));
// SAFETY: both buffers are NUL-terminated UTF-16 that outlive the call.
if unsafe {
windows_sys::Win32::Storage::FileSystem::MoveFileExW(from.as_ptr(), to.as_ptr(), 0)
} != 0
{
if unsafe { windows_sys::Win32::Storage::FileSystem::MoveFileExW(from.as_ptr(), to.as_ptr(), 0) } != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
@@ -57,10 +49,7 @@ pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
let _ = (source, destination);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"atomic no-replace directory publication requires Linux or macOS",
))
Err(io::Error::new(io::ErrorKind::Unsupported, "atomic no-replace directory publication requires Linux or macOS"))
}
#[cfg(all(test, target_os = "windows"))]
@@ -96,10 +85,7 @@ mod tests {
let path = std::env::temp_dir().join(format!(
"strata-publish-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
));
fs::create_dir(&path).unwrap();
Self(path)
@@ -130,12 +116,7 @@ mod tests {
"empty" => assert_eq!(fs::read_dir(target).unwrap().count(), 0),
"nonempty" => assert_eq!(fs::read(target.join("original")).unwrap(), b"keep"),
"file" => assert_eq!(fs::read(target).unwrap(), b"keep"),
_ => assert!(
fs::symlink_metadata(target)
.unwrap()
.file_type()
.is_symlink()
),
_ => assert!(fs::symlink_metadata(target).unwrap().file_type().is_symlink()),
}
}
@@ -149,10 +130,7 @@ mod tests {
let target = root.0.join(kind);
make_conflict(kind, &root, &source, &target);
let before = fs::symlink_metadata(&target).unwrap();
assert_eq!(
publish(&source, &target).unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(publish(&source, &target).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::symlink_metadata(&target).unwrap().ino(), before.ino());
assert_eq!(fs::read(source.join("payload")).unwrap(), b"complete bytes");
assert_conflict_untouched(kind, &target);
@@ -160,8 +138,7 @@ mod tests {
#[cfg(target_os = "linux")]
let target = {
use std::os::unix::ffi::OsStringExt;
root.0
.join(std::ffi::OsString::from_vec(b"pack-\xff".to_vec()))
root.0.join(std::ffi::OsString::from_vec(b"pack-\xff".to_vec()))
};
// APFS rejects invalid UTF-8 filenames independently of rename flags.
#[cfg(target_os = "macos")]
@@ -179,20 +156,11 @@ mod tests {
assert_eq!(results.iter().filter(|(_, _, r)| r.is_ok()).count(), 1);
let (winner, source, _) = results.iter().find(|(_, _, r)| r.is_ok()).unwrap();
assert!(!source.exists());
assert_eq!(
fs::read(target.join("payload")).unwrap(),
vec![*winner; 1024]
);
assert_eq!(fs::read(target.join("payload")).unwrap(), vec![*winner; 1024]);
assert_eq!(fs::read(target.join("receipt")).unwrap(), [*winner]);
let (loser, source, error) = results.iter().find(|(_, _, r)| r.is_err()).unwrap();
assert_eq!(
error.as_ref().unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(
fs::read(source.join("payload")).unwrap(),
vec![*loser; 1024]
);
assert_eq!(error.as_ref().unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read(source.join("payload")).unwrap(), vec![*loser; 1024]);
assert_eq!(fs::read(source.join("receipt")).unwrap(), [*loser]);
}
@@ -214,9 +182,6 @@ mod tests {
(number, source.clone(), publish(&source, &target))
}));
}
handles
.into_iter()
.map(|h| h.join().unwrap())
.collect::<Vec<_>>()
handles.into_iter().map(|h| h.join().unwrap()).collect::<Vec<_>>()
}
}
+26 -101
View File
@@ -10,8 +10,8 @@ use sha2::{Digest, Sha256};
use crate::{kar_codec, model::Manifest};
use leleka_model_format::kar::{DecodeSource, ElementRange, KarInspection};
pub use leleka_model_format::kar::KarSummary as Summary;
use leleka_model_format::kar::{DecodeSource, ElementRange, KarInspection};
#[derive(Debug)]
pub struct TensorSource {
pub name: String,
@@ -37,24 +37,17 @@ impl TensorSource {
return Ok(self.section_bytes);
}
if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max {
return Err(format!(
"{}: KAR level {level} is outside its supported dial",
self.name
));
return Err(format!("{}: KAR level {level} is outside its supported dial", self.name));
}
self.planes_offset
.checked_sub(self.section_offset)
.and_then(|prefix| {
prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes))
})
.and_then(|prefix| prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)))
.filter(|bytes| *bytes <= self.section_bytes)
.ok_or_else(|| format!("{}: invalid KAR GPU prefix size", self.name))
}
pub fn gpu_decode_bytes(&self) -> Result<u64, String> {
self.n_elements
.checked_mul(4)
.ok_or_else(|| format!("{}: KAR F32 decode size overflow", self.name))
self.n_elements.checked_mul(4).ok_or_else(|| format!("{}: KAR F32 decode size overflow", self.name))
}
/// One-row output size for a geometrically addressable NESTED table.
@@ -99,12 +92,8 @@ pub(crate) use leleka_model_format::kar::{crc32, crc32_step};
/// The shared KAR scalar decoder behind the inspector's callback shape.
fn scalar_decode(source: &DecodeSource<'_>, start: usize, output: &mut [f32]) -> Result<(), String> {
let prefix = kar_codec::KarPrefix {
scales: source.scales,
book: source.book,
planes: source.planes,
group: source.group,
};
let prefix =
kar_codec::KarPrefix { scales: source.scales, book: source.book, planes: source.planes, group: source.group };
kar_codec::decode_range(&prefix, start, output)
}
@@ -119,17 +108,10 @@ impl VerifiedRangeDecoder {
}
pub(crate) fn open_previously_verified(path: &Path) -> Result<Self, String> {
Ok(Self {
reader: KarInspection::inspect(File::open(path).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())?,
reader: KarInspection::inspect(File::open(path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?,
})
}
pub fn decode_range(
&mut self,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Result<Vec<f32>, String> {
pub fn decode_range(&mut self, name: &str, level: u8, start: usize, count: usize) -> Result<Vec<f32>, String> {
self.reader.decode_range(name, level, ElementRange { start, count }, scalar_decode).map_err(|e| e.to_string())
}
pub fn element_count(&self, name: &str) -> Result<usize, String> {
@@ -148,15 +130,7 @@ pub fn inspect(path: &Path) -> Result<Summary, String> {
}
pub fn inspect_with_sources(path: &Path) -> Result<(Summary, Vec<TensorSource>), String> {
let reader = open_inspection(path)?;
Ok((
reader.summary().clone(),
reader
.tensor_sources()
.iter()
.cloned()
.map(TensorSource::from)
.collect(),
))
Ok((reader.summary().clone(), reader.tensor_sources().iter().cloned().map(TensorSource::from).collect()))
}
pub fn verify(path: &Path) -> Result<Summary, String> {
Ok(verify_with_sources(path)?.0)
@@ -171,60 +145,31 @@ pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result<Vec<f
/// Decode at most one million values from an arbitrary offset of a nested
/// tensor. Only the relevant scales and plane words are read into memory.
/// This is a CPU quality oracle, not a serving implementation.
pub fn decode_tensor_range(
path: &Path,
name: &str,
level: u8,
start: usize,
count: usize,
) -> Result<Vec<f32>, String> {
pub fn decode_tensor_range(path: &Path, name: &str, level: u8, start: usize, count: usize) -> Result<Vec<f32>, String> {
decode_tensor_inner(path, name, level, start, Some(count))
}
/// The row length of a record that the CUDA row gather can read: compressed, divisible by 32, at most a million.
fn gather_row_length(record: &TensorSource) -> Result<usize, String> {
let row_len = usize::try_from(
*record
.dimensions
.first()
.ok_or("KAR tensor has no dimensions")?,
)
.map_err(|_| "KAR row length is too large")?;
if record.storage_class != 0
|| row_len == 0
|| !row_len.is_multiple_of(32)
|| row_len > 1_000_000
{
return Err(
"CUDA row gather requires a compressed record with a row length divisible by 32 \
let row_len = usize::try_from(*record.dimensions.first().ok_or("KAR tensor has no dimensions")?)
.map_err(|_| "KAR row length is too large")?;
if record.storage_class != 0 || row_len == 0 || !row_len.is_multiple_of(32) || row_len > 1_000_000 {
return Err("CUDA row gather requires a compressed record with a row length divisible by 32 \
and at most one million values"
.into(),
);
.into());
}
Ok(row_len)
}
/// CPU parity oracle for one CUDA row-gather request. The entire archive is
/// verified before the bounded row is decoded.
pub fn decode_tensor_row(
path: &Path,
name: &str,
level: u8,
row_id: u32,
) -> Result<Vec<f32>, String> {
pub fn decode_tensor_row(path: &Path, name: &str, level: u8, row_id: u32) -> Result<Vec<f32>, String> {
let (_, records) = inspect_with_sources(path)?;
let record = records
.iter()
.find(|record| record.name == name)
.ok_or_else(|| format!("KAR tensor not found: {name}"))?;
let record =
records.iter().find(|record| record.name == name).ok_or_else(|| format!("KAR tensor not found: {name}"))?;
let row_len = gather_row_length(record)?;
let start = (row_id as usize)
.checked_mul(row_len)
.ok_or("KAR row offset overflow")?;
if start
.checked_add(row_len)
.is_none_or(|end| end as u64 > record.n_elements)
{
let start = (row_id as usize).checked_mul(row_len).ok_or("KAR row offset overflow")?;
if start.checked_add(row_len).is_none_or(|end| end as u64 > record.n_elements) {
return Err("KAR row ID exceeds tensor bounds".into());
}
decode_tensor_range(path, name, level, start, row_len)
@@ -246,23 +191,13 @@ pub fn f32_fnv1a64(values: &[f32]) -> u64 {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
})
.fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3))
}
pub fn verify_with_sources(path: &Path) -> Result<(Summary, Vec<TensorSource>), String> {
let mut reader = open_inspection(path)?;
reader.verify_payloads().map_err(|e| e.to_string())?;
Ok((
reader.summary().clone(),
reader
.tensor_sources()
.iter()
.cloned()
.map(TensorSource::from)
.collect(),
))
Ok((reader.summary().clone(), reader.tensor_sources().iter().cloned().map(TensorSource::from).collect()))
}
fn check_shard_name(name: &str) -> Result<(), String> {
let mut components = Path::new(name).components();
@@ -274,8 +209,7 @@ fn check_shard_name(name: &str) -> Result<(), String> {
/// Opens a manifest shard and checks its length against the manifest.
fn open_shard(entry: &crate::model::ModelFile, source_dir: &Path) -> Result<(File, u64), String> {
let file = File::open(source_dir.join(&entry.name))
.map_err(|error| format!("{}: {error}", entry.name))?;
let file = File::open(source_dir.join(&entry.name)).map_err(|error| format!("{}: {error}", entry.name))?;
let size = file.metadata().map_err(|error| error.to_string())?.len();
if size != entry.size {
return Err(format!("{}: source size differs from manifest", entry.name));
@@ -300,19 +234,12 @@ fn hash_shard(
combined.update(&buffer[..read]);
}
if hex::encode(individual.finalize()) != entry.sha256.to_ascii_lowercase() {
return Err(format!(
"{}: source SHA-256 differs from manifest",
entry.name
));
return Err(format!("{}: source SHA-256 differs from manifest", entry.name));
}
Ok(())
}
pub fn verify_source_files(
summary: &Summary,
manifest: &Manifest,
source_dir: &Path,
) -> Result<(), String> {
pub fn verify_source_files(summary: &Summary, manifest: &Manifest, source_dir: &Path) -> Result<(), String> {
let mut files = manifest.files.iter().collect::<Vec<_>>();
if files.is_empty() {
return Err("source manifest has no files".into());
@@ -324,9 +251,7 @@ pub fn verify_source_files(
for entry in files {
check_shard_name(&entry.name)?;
let (mut file, size) = open_shard(entry, source_dir)?;
total = total
.checked_add(size)
.ok_or("source byte count overflow")?;
total = total.checked_add(size).ok_or("source byte count overflow")?;
hash_shard(&mut file, entry, &mut buffer, &mut combined)?;
}
if total != summary.source_bytes || combined.finalize().as_slice() != summary.source_digest {
+4 -17
View File
@@ -29,10 +29,7 @@ fn two_shard_manifest() -> Manifest {
size: 3,
sha256: sha(bytes),
};
Manifest {
schema_version: 1,
files: vec![shard("b", b"def"), shard("a", b"abc")],
}
Manifest { schema_version: 1, files: vec![shard("b", b"def"), shard("a", b"abc")] }
}
fn abcdef_summary() -> Summary {
@@ -60,11 +57,7 @@ fn source_identity_uses_verified_shards_in_filename_order() {
let summary = abcdef_summary();
verify_source_files(&summary, &manifest, &root).unwrap();
fs::write(root.join("b.gguf"), b"xyz").unwrap();
assert!(
verify_source_files(&summary, &manifest, &root)
.unwrap_err()
.contains("SHA-256")
);
assert!(verify_source_files(&summary, &manifest, &root).unwrap_err().contains("SHA-256"));
fs::remove_dir_all(root).unwrap();
}
@@ -168,10 +161,7 @@ fn assert_raw_archive_summary(path: &std::path::Path) {
fn assert_raw_archive_range_decodes(path: &std::path::Path) {
let mut decoder = VerifiedRangeDecoder::open(path).unwrap();
assert_eq!(decoder.element_count("weight").unwrap(), 64);
assert_eq!(
decoder.decode_range("weight", 0, 8, 4).unwrap(),
vec![0.0; 4]
);
assert_eq!(decoder.decode_range("weight", 0, 8, 4).unwrap(), vec![0.0; 4]);
}
fn assert_nested_archive_detects_payload_corruption(path: &std::path::Path, nested: &mut [u8]) {
@@ -249,10 +239,7 @@ fn bounded_archive_range_decode_crosses_scale_and_plane_groups() {
write_range_fixture(&path);
let full = decode_preview_tensor(&path, "expert", 2).unwrap();
for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] {
assert_eq!(
decode_tensor_range(&path, "expert", 2, start, count).unwrap(),
full[start..start + count]
);
assert_eq!(decode_tensor_range(&path, "expert", 2, start, count).unwrap(), full[start..start + count]);
}
assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err());
assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err());
+5 -27
View File
@@ -130,34 +130,12 @@ mod tests {
}
fn assert_three_level_oracle() {
let varied = [
-1.0, -0.93, -0.8, -0.65, -0.49, -0.3, -0.15, -0.05, 0.05, 0.14, 0.29, 0.43, 0.6, 0.77,
0.91, 1.0,
];
let varied =
[-1.0, -0.93, -0.8, -0.65, -0.49, -0.3, -0.15, -0.05, 0.05, 0.14, 0.29, 0.43, 0.6, 0.77, 0.91, 1.0];
let calibration = fit_topdown(&varied, 3).unwrap();
let bits = calibration
.boundaries
.iter()
.map(|v| v.to_bits())
.collect::<Vec<_>>();
assert_eq!(
bits,
[
0xbf5d_70a4,
0xbf11_eb85,
0xbe66_6667,
0,
0x3e5c_28f6,
0x3f03_d70a,
0x3f57_0a3e
]
);
assert_eq!(
calibration.books[2],
[
0xbbb8, 0xb9cd, 0xb652, 0xae66, 0x2e14, 0x35c3, 0x397b, 0x3ba4
]
);
let bits = calibration.boundaries.iter().map(|v| v.to_bits()).collect::<Vec<_>>();
assert_eq!(bits, [0xbf5d_70a4, 0xbf11_eb85, 0xbe66_6667, 0, 0x3e5c_28f6, 0x3f03_d70a, 0x3f57_0a3e]);
assert_eq!(calibration.books[2], [0xbbb8, 0xb9cd, 0xb652, 0xae66, 0x2e14, 0x35c3, 0x397b, 0x3ba4]);
}
#[test]
+12 -52
View File
@@ -21,10 +21,8 @@ const BOUNDARIES: [f32; 3] = [-0.5, 0.0, 0.5];
const BOOK1: [u16; 2] = [0xb800, 0x3800];
const BOOK2: [u16; 4] = [0xba00, 0xb400, 0x3400, 0x3a00];
const BOOKS: [&[u16]; 2] = [&BOOK1, &BOOK2];
const PLE_PART_NAMES: [&str; 2] = [
"per_layer_token_embd.weight#strata-part-001-of-002",
"per_layer_token_embd.weight#strata-part-002-of-002",
];
const PLE_PART_NAMES: [&str; 2] =
["per_layer_token_embd.weight#strata-part-001-of-002", "per_layer_token_embd.weight#strata-part-002-of-002"];
fn raw_bytes(weights: &[f32]) -> Vec<u8> {
let mut raw = Vec::with_capacity(weights.len() * 4);
@@ -50,12 +48,7 @@ fn nested<'a>(scales: &'a [u16], planes: &'a [&'a [u32]]) -> kar_writer::TensorD
}
}
fn identity<'a>(
name: &'a str,
builder: &'a str,
weights: &[f32],
raw: &[u8],
) -> kar_writer::SourceIdentity<'a> {
fn identity<'a>(name: &'a str, builder: &'a str, weights: &[f32], raw: &[u8]) -> kar_writer::SourceIdentity<'a> {
kar_writer::SourceIdentity {
name,
architecture: "synthetic",
@@ -100,25 +93,16 @@ fn ple_part<'a>(
}
fn ple_source<'a>(weights: &[f32], raw: &[u8]) -> kar_writer::SourceIdentity<'a> {
identity(
"leleka-api-ple-smoke-f32",
"leleka-api/ple-smoke-topdown-g32-l2-v1",
weights,
raw,
)
identity("leleka-api-ple-smoke-f32", "leleka-api/ple-smoke-topdown-g32-l2-v1", weights, raw)
}
fn ple_summary(destination: &Path) -> Result<PleFixtureSummary, String> {
let mut row_fnv1a64 = [0; 4];
for (row, checksum) in row_fnv1a64.iter_mut().enumerate() {
let values =
kar::decode_tensor_row(destination, PLE_PART_NAMES[row / 2], 2, (row % 2) as u32)?;
let values = kar::decode_tensor_row(destination, PLE_PART_NAMES[row / 2], 2, (row % 2) as u32)?;
*checksum = kar::f32_fnv1a64(&values);
}
Ok(PleFixtureSummary {
archive_digest: file_digest(destination)?,
row_fnv1a64,
})
Ok(PleFixtureSummary { archive_digest: file_digest(destination)?, row_fnv1a64 })
}
/// Four PLE-shaped rows in two KAR parts, for the optional Strata PLE reader.
@@ -131,20 +115,8 @@ pub fn write_ple(destination: &Path) -> Result<PleFixtureSummary, String> {
let first_planes = plane_slices(&first.planes);
let second_planes = plane_slices(&second.planes);
let tensors = [
ple_part(
PLE_PART_NAMES[0],
0,
&raw[..1280],
&first.scales,
&first_planes,
),
ple_part(
PLE_PART_NAMES[1],
1280,
&raw[1280..],
&second.scales,
&second_planes,
),
ple_part(PLE_PART_NAMES[0], 0, &raw[..1280], &first.scales, &first_planes),
ple_part(PLE_PART_NAMES[1], 1280, &raw[1280..], &second.scales, &second_planes),
];
kar_writer::write_archive(destination, &source, &tensors)?;
ple_summary(destination)
@@ -155,12 +127,7 @@ pub fn write(destination: &Path) -> Result<FixtureSummary, String> {
let encoded = kar_codec::encode_with_boundaries(&weights, 32, &BOUNDARIES, 2)?;
let planes = plane_slices(&encoded.planes);
let raw = raw_bytes(&weights);
let source = identity(
"leleka-api-smoke-f32",
"leleka-api/smoke-topdown-g32-l2-v1",
&weights,
&raw,
);
let source = identity("leleka-api-smoke-f32", "leleka-api/smoke-topdown-g32-l2-v1", &weights, &raw);
let tensor = [kar_writer::Tensor {
name: "smoke.expert",
dims: &[32],
@@ -188,20 +155,14 @@ mod tests {
let path = std::env::temp_dir().join(format!(
"strata-kar-fixture-{}-{}.kar",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()
));
let created = write(&path).unwrap();
assert_eq!(created.archive.tensor_count, 1);
let decoded = kar::decode_preview_tensor(&path, "smoke.expert", 2).unwrap();
assert_eq!(&decoded[..4], &[-0.75, -0.25, 0.25, 0.75]);
assert_eq!(created.decoded_fnv1a64, kar::f32_fnv1a64(&decoded));
assert_eq!(
kar::decode_tensor_row(&path, "smoke.expert", 2, 0).unwrap(),
decoded
);
assert_eq!(kar::decode_tensor_row(&path, "smoke.expert", 2, 0).unwrap(), decoded);
assert!(kar::decode_tensor_row(&path, "smoke.expert", 2, 1).is_err());
assert!(write(&path).is_err());
std::fs::remove_file(path).unwrap();
@@ -209,8 +170,7 @@ mod tests {
#[test]
fn ple_fixture_has_two_ordered_parts_and_four_rows() {
let path =
std::env::temp_dir().join(format!("strata-ple-fixture-{}.kar", std::process::id()));
let path = std::env::temp_dir().join(format!("strata-ple-fixture-{}.kar", std::process::id()));
let created = write_ple(&path).unwrap();
assert_eq!(kar::verify(&path).unwrap().tensor_count, 2);
assert_ne!(created.row_fnv1a64[0], created.row_fnv1a64[1]);
+20 -78
View File
@@ -82,23 +82,12 @@ struct Measured {
}
impl Measured {
fn of(
source: &kar::TensorSource,
level: u8,
peak_overflow: &'static str,
) -> Result<Self, String> {
fn of(source: &kar::TensorSource, level: u8, peak_overflow: &'static str) -> Result<Self, String> {
let compressed = source.gpu_resident_bytes(level)?;
let scratch = source.gpu_decode_bytes()?;
let peak = compressed.checked_add(scratch).ok_or(peak_overflow)?;
let one_row_peak = source
.gpu_one_row_decode_bytes()
.and_then(|row_bytes| compressed.checked_add(row_bytes));
Ok(Self {
compressed,
scratch,
peak,
one_row_peak,
})
let one_row_peak = source.gpu_one_row_decode_bytes().and_then(|row_bytes| compressed.checked_add(row_bytes));
Ok(Self { compressed, scratch, peak, one_row_peak })
}
fn record(&self, name: String) -> RecordMemory {
@@ -123,13 +112,7 @@ struct Tally {
impl Tally {
fn new(budget: u64) -> Self {
Self {
budget,
scratch_max: 0,
peak_max: 0,
exceeding: 0,
row_fits: 0,
}
Self { budget, scratch_max: 0, peak_max: 0, exceeding: 0, row_fits: 0 }
}
fn observe(&mut self, measured: &Measured) {
@@ -138,20 +121,14 @@ impl Tally {
if measured.peak > self.budget {
self.exceeding += 1;
}
if measured.peak > self.budget
&& measured
.one_row_peak
.is_some_and(|bytes| bytes <= self.budget)
{
if measured.peak > self.budget && measured.one_row_peak.is_some_and(|bytes| bytes <= self.budget) {
self.row_fits += 1;
}
}
}
fn by_peak_then_name(a: &RecordMemory, b: &RecordMemory) -> std::cmp::Ordering {
b.single_record_peak_bytes
.cmp(&a.single_record_peak_bytes)
.then_with(|| a.name.cmp(&b.name))
b.single_record_peak_bytes.cmp(&a.single_record_peak_bytes).then_with(|| a.name.cmp(&b.name))
}
fn keep_largest<T>(list: &mut Vec<T>, memory: impl Fn(&T) -> &RecordMemory) {
@@ -168,26 +145,18 @@ struct SelectedSources {
}
impl SelectedSources {
fn lookup(
&self,
selected: &kar_overlay::ResolvedRecord,
) -> Result<(&kar::TensorSource, u8), String> {
fn lookup(&self, selected: &kar_overlay::ResolvedRecord) -> Result<(&kar::TensorSource, u8), String> {
let (list, level) = match selected.archive {
"base" => (&self.base, self.base_level),
"overlay" => (&self.overlay, self.overlay_level),
_ => return Err("unknown KAR selection archive".into()),
};
let source = list
.get(selected.archive_index)
.ok_or("selected KAR record index is out of bounds")?;
let source = list.get(selected.archive_index).ok_or("selected KAR record index is out of bounds")?;
Ok((source, level))
}
}
fn check_selected_unchanged(
source: &kar::TensorSource,
selected: &kar_overlay::ResolvedRecord,
) -> Result<(), String> {
fn check_selected_unchanged(source: &kar::TensorSource, selected: &kar_overlay::ResolvedRecord) -> Result<(), String> {
if source.name != selected.name
|| source.offset != selected.source_offset
|| source.dimensions != selected.dimensions
@@ -208,21 +177,13 @@ struct SelectedTotals {
impl SelectedTotals {
fn add_compressed(&mut self, from_base: bool, compressed: u64) -> Result<(), String> {
let total = if from_base {
&mut self.base_bytes
} else {
&mut self.overlay_bytes
};
*total = total
.checked_add(compressed)
.ok_or("selected KAR compressed total overflow")?;
let total = if from_base { &mut self.base_bytes } else { &mut self.overlay_bytes };
*total = total.checked_add(compressed).ok_or("selected KAR compressed total overflow")?;
Ok(())
}
fn selected_bytes(&self) -> Result<u64, String> {
self.base_bytes
.checked_add(self.overlay_bytes)
.ok_or_else(|| "selected KAR compressed total overflow".into())
self.base_bytes.checked_add(self.overlay_bytes).ok_or_else(|| "selected KAR compressed total overflow".into())
}
fn all_plus_scratch(&self, selected_bytes: u64) -> Result<u64, String> {
@@ -274,12 +235,7 @@ pub fn plan_selected(
let selection = kar_overlay::resolve_verified(base_path, overlay_path)?;
let (_, base) = kar::inspect_with_sources(base_path)?;
let (_, overlay) = kar::inspect_with_sources(overlay_path)?;
let sources = SelectedSources {
base,
overlay,
base_level,
overlay_level,
};
let sources = SelectedSources { base, overlay, base_level, overlay_level };
let totals = walk_selected(&selection, &sources, budget_bytes)?;
selected_report(selection, totals, &sources, budget_bytes)
}
@@ -313,11 +269,7 @@ struct ArchiveTotals {
largest: Vec<RecordMemory>,
}
fn walk_archive(
records: Vec<kar::TensorSource>,
level: u8,
budget_bytes: u64,
) -> Result<ArchiveTotals, String> {
fn walk_archive(records: Vec<kar::TensorSource>, level: u8, budget_bytes: u64) -> Result<ArchiveTotals, String> {
let mut totals = ArchiveTotals {
compressed_total: 0,
tally: Tally::new(budget_bytes),
@@ -325,10 +277,8 @@ fn walk_archive(
};
for record in records {
let measured = Measured::of(&record, level, "KAR single-record GPU peak overflow")?;
totals.compressed_total = totals
.compressed_total
.checked_add(measured.compressed)
.ok_or("KAR total GPU residency overflow")?;
totals.compressed_total =
totals.compressed_total.checked_add(measured.compressed).ok_or("KAR total GPU residency overflow")?;
totals.tally.observe(&measured);
totals.largest.push(measured.record(record.name));
}
@@ -342,10 +292,8 @@ pub fn plan(path: &Path, level: u8, budget_bytes: u64) -> Result<Report, String>
}
let (summary, records) = kar::inspect_with_sources(path)?;
let totals = walk_archive(records, level, budget_bytes)?;
let all_plus_scratch = totals
.compressed_total
.checked_add(totals.tally.scratch_max)
.ok_or("KAR all-resident GPU peak overflow")?;
let all_plus_scratch =
totals.compressed_total.checked_add(totals.tally.scratch_max).ok_or("KAR all-resident GPU peak overflow")?;
Ok(Report {
schema: "leleka-api/kar-gpu-memory-plan-v1",
level,
@@ -369,14 +317,8 @@ mod tests {
#[test]
fn smoke_fixture_has_bounded_single_record_peak() {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"strata-kar-memory-{}-{nonce}.kar",
std::process::id()
));
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("strata-kar-memory-{}-{nonce}.kar", std::process::id()));
crate::kar_fixture::write(&path).unwrap();
let report = plan(&path, 2, 1 << 20).unwrap();
assert_eq!(report.record_count, 1);
+1 -4
View File
@@ -11,10 +11,7 @@ use std::{
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::{
gguf, gguf_f32_stream, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer,
model::Manifest,
};
use crate::{gguf, gguf_f32_stream, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer, model::Manifest};
#[derive(Deserialize)]
struct Candidates {
@@ -26,18 +26,12 @@ pub(super) fn candidate_source<'a>(
locations: &HashMap<String, Location>,
name: &str,
) -> Result<CandidateSource<'a>, String> {
if let Some(parent) = base
.partitioned_tensors
.iter()
.find(|parent| parent.parts.iter().any(|part| part.name == name))
if let Some(parent) =
base.partitioned_tensors.iter().find(|parent| parent.parts.iter().any(|part| part.name == name))
{
return partition_source(base, parent, locations, name);
}
if base
.partitioned_tensors
.iter()
.any(|parent| parent.parent_name == name)
{
if base.partitioned_tensors.iter().any(|parent| parent.parent_name == name) {
return Err(format!("{name}: partition parent is not a KAR record"));
}
whole_source(base, locations, name)
@@ -48,14 +42,9 @@ fn whole_source<'a>(
locations: &HashMap<String, Location>,
name: &str,
) -> Result<CandidateSource<'a>, String> {
let original = base
.tensors
.iter()
.find(|tensor| tensor.name == name)
.ok_or("candidate absent from base provenance")?;
let location = locations
.get(name)
.ok_or("candidate absent from GGUF source")?;
let original =
base.tensors.iter().find(|tensor| tensor.name == name).ok_or("candidate absent from base provenance")?;
let location = locations.get(name).ok_or("candidate absent from GGUF source")?;
if location.kind != original.source_kind {
return Err(format!("{name}: source kind differs from base"));
}
@@ -113,43 +102,22 @@ impl<'a, 'l> PartitionView<'a, 'l> {
.iter()
.find(|tensor| tensor.name == parent.parent_name)
.ok_or("partition parent absent from base provenance")?;
let location = locations
.get(&parent.parent_name)
.ok_or("partition parent absent from GGUF source")?;
let location = locations.get(&parent.parent_name).ok_or("partition parent absent from GGUF source")?;
let (block_elements, block_bytes) =
gguf::block_geometry(parent.source_kind).ok_or("unsupported partition source kind")?;
Ok(Self {
parent,
part,
original,
location,
block_elements,
block_bytes,
})
Ok(Self { parent, part, original, location, block_elements, block_bytes })
}
fn extent(&self) -> Result<PartitionExtent, String> {
let part = self.part;
let elements = part
.dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or("partition shape overflow")?;
let raw_end = part
.source_byte_offset
.checked_add(part.source_bytes)
.ok_or("partition source offset overflow")?;
let derived_end = part
.derived_offset
.checked_add(part.derived_bytes)
.ok_or("partition derived offset overflow")?;
let elements =
part.dimensions.iter().try_fold(1u64, |n, dim| n.checked_mul(*dim)).ok_or("partition shape overflow")?;
let raw_end =
part.source_byte_offset.checked_add(part.source_bytes).ok_or("partition source offset overflow")?;
let derived_end =
part.derived_offset.checked_add(part.derived_bytes).ok_or("partition derived offset overflow")?;
let expected_offset = self.expected_offset()?;
Ok(PartitionExtent {
elements,
raw_end,
derived_end,
expected_offset,
})
Ok(PartitionExtent { elements, raw_end, derived_end, expected_offset })
}
fn expected_offset(&self) -> Result<u64, String> {
+19 -74
View File
@@ -19,8 +19,7 @@ pub fn compare(
) -> Result<Comparison, String> {
let (base, overlay) = read_provenances(base_archive, overlay_archive)?;
check_provenance(&base, &overlay, overlay_archive)?;
let (base_sources, overlay_sources) =
check_source_identity(base_archive, overlay_archive, &base, &overlay)?;
let (base_sources, overlay_sources) = check_source_identity(base_archive, overlay_archive, &base, &overlay)?;
check_unique_overlay_names(&overlay)?;
let locations = locate_shards(manifest, source_dir, &base)?;
let mut comparer = Comparer {
@@ -50,11 +49,7 @@ fn read_provenances(
Ok((read_json(base_sidecar)?, read_json(overlay_sidecar)?))
}
fn check_provenance(
base: &BaseProvenance,
overlay: &OverlayProvenance,
overlay_archive: &Path,
) -> Result<(), String> {
fn check_provenance(base: &BaseProvenance, overlay: &OverlayProvenance, overlay_archive: &Path) -> Result<(), String> {
if !base.supported_partition_policy()
|| overlay.schema != "leleka-api/kar-overlay-provenance-v1"
|| overlay.base_archive_sha256 != base.archive_sha256
@@ -86,11 +81,7 @@ fn check_source_identity(
}
fn check_unique_overlay_names(overlay: &OverlayProvenance) -> Result<(), String> {
let names = overlay
.records
.iter()
.map(|record| record.name.as_str())
.collect::<HashSet<_>>();
let names = overlay.records.iter().map(|record| record.name.as_str()).collect::<HashSet<_>>();
if names.len() != overlay.records.len() {
return Err("duplicate overlay tensor name".into());
}
@@ -109,10 +100,7 @@ fn locate_shards(
}
let mut locations = HashMap::new();
for (entry, shard) in files.iter().zip(&base.shards) {
if entry.name != shard.name
|| entry.size != shard.gguf_bytes
|| entry.sha256 != shard.gguf_sha256
{
if entry.name != shard.name || entry.size != shard.gguf_bytes || entry.sha256 != shard.gguf_sha256 {
return Err("source manifest differs from base provenance".into());
}
let path = source_dir.join(&entry.name);
@@ -136,10 +124,7 @@ struct Comparer<'a> {
}
impl Comparer<'_> {
fn compare_all(
&mut self,
overlay_sources: &[kar::TensorSource],
) -> Result<Vec<ComparedRecord>, String> {
fn compare_all(&mut self, overlay_sources: &[kar::TensorSource]) -> Result<Vec<ComparedRecord>, String> {
let overlay = self.overlay;
let mut compared = Vec::with_capacity(overlay.records.len());
for (record, overlay_source) in overlay.records.iter().zip(overlay_sources) {
@@ -154,17 +139,11 @@ impl Comparer<'_> {
overlay_source: &kar::TensorSource,
) -> Result<ComparedRecord, String> {
let selected = candidate_source(self.base, self.locations, &record.name)?;
let base_source = self
.base_records
.get(record.name.as_str())
.ok_or("selected tensor absent from base KAR directory")?;
let base_source =
self.base_records.get(record.name.as_str()).ok_or("selected tensor absent from base KAR directory")?;
let f32_digest = parse_digest(&record.f32_sha256)?;
let elements =
shape_elements(&selected.location.dimensions).ok_or("GGUF tensor shape overflow")?;
let sources = SourcePair {
base: base_source,
overlay: overlay_source,
};
let elements = shape_elements(&selected.location.dimensions).ok_or("GGUF tensor shape overflow")?;
let sources = SourcePair { base: base_source, overlay: overlay_source };
if sources.identity_differs(record, &selected, f32_digest)
|| sources.offsets_differ(record, &selected, f32_digest, elements)?
{
@@ -192,10 +171,7 @@ impl Comparer<'_> {
|raw, f32_bytes| self.decode_chunk(&mut sums, &record.name, raw, f32_bytes),
)?;
if sums.digests_differ(decoded_bytes, elements, selected.source_sha256, f32_digest)? {
return Err(format!(
"{}: selected GGUF source digest mismatch",
record.name
));
return Err(format!("{}: selected GGUF source digest mismatch", record.name));
}
Ok(sums)
}
@@ -203,23 +179,13 @@ impl Comparer<'_> {
impl Comparer<'_> {
/// Hash one streamed chunk and add its squared errors against the base and overlay reconstructions.
fn decode_chunk(
&mut self,
sums: &mut ErrorSums,
name: &str,
raw: &[u8],
f32_bytes: &[u8],
) -> Result<(), String> {
fn decode_chunk(&mut self, sums: &mut ErrorSums, name: &str, raw: &[u8], f32_bytes: &[u8]) -> Result<(), String> {
sums.raw_hash.update(raw);
sums.f32_hash.update(f32_bytes);
let count = f32_bytes.len() / 4;
let base_values = self
.base_decoder
.decode_range(name, 2, sums.position, count)?;
let base_values = self.base_decoder.decode_range(name, 2, sums.position, count)?;
let levels = self.overlay.levels;
let overlay_values =
self.overlay_decoder
.decode_range(name, levels, sums.position, count)?;
let overlay_values = self.overlay_decoder.decode_range(name, levels, sums.position, count)?;
sums.accumulate(f32_bytes, &base_values, &overlay_values);
sums.position += count;
Ok(())
@@ -233,12 +199,7 @@ struct SourcePair<'a> {
}
impl SourcePair<'_> {
fn identity_differs(
&self,
record: &OverlayRecord,
selected: &CandidateSource,
f32_digest: [u8; 32],
) -> bool {
fn identity_differs(&self, record: &OverlayRecord, selected: &CandidateSource, f32_digest: [u8; 32]) -> bool {
let dimensions = &selected.location.dimensions;
self.overlay.name != record.name
|| self.base.digest != f32_digest
@@ -287,12 +248,8 @@ impl Default for ErrorSums {
impl ErrorSums {
fn accumulate(&mut self, f32_bytes: &[u8], base_values: &[f32], overlay_values: &[f32]) {
for ((word, base_value), overlay_value) in f32_bytes
.as_chunks::<4>()
.0
.iter()
.zip(base_values)
.zip(overlay_values)
for ((word, base_value), overlay_value) in
f32_bytes.as_chunks::<4>().0.iter().zip(base_values).zip(overlay_values)
{
let original = f64::from(f32::from_le_bytes(*word));
self.reference_sum += original * original;
@@ -315,28 +272,16 @@ impl ErrorSums {
}
fn into_record(self, record: &OverlayRecord, elements: u64) -> Result<ComparedRecord, String> {
let denominator = if self.reference_sum == 0.0 {
1.0
} else {
self.reference_sum
};
let denominator = if self.reference_sum == 0.0 { 1.0 } else { self.reference_sum };
let base_relative_l2 = (self.base_error / denominator).sqrt();
let overlay_relative_l2 = (self.overlay_error / denominator).sqrt();
if !base_relative_l2.is_finite()
|| !overlay_relative_l2.is_finite()
|| (overlay_relative_l2 - record.relative_l2).abs() > 1e-6
{
return Err(format!(
"{}: overlay reconstruction differs from encoding",
record.name
));
return Err(format!("{}: overlay reconstruction differs from encoding", record.name));
}
Ok(ComparedRecord {
name: record.name.clone(),
elements,
base_relative_l2,
overlay_relative_l2,
})
Ok(ComparedRecord { name: record.name.clone(), elements, base_relative_l2, overlay_relative_l2 })
}
}
+15 -57
View File
@@ -52,18 +52,12 @@ impl Encoder<'_> {
fn encode_one(&self, candidate: &Candidate, ordinal: usize) -> Result<Prepared, String> {
let selected = candidate_source(self.base, self.locations, &candidate.name)?;
let location = &selected.location;
let elements =
shape_elements(&location.dimensions).ok_or("candidate tensor shape overflow")?;
let elements = shape_elements(&location.dimensions).ok_or("candidate tensor shape overflow")?;
self.check_geometry(candidate, &selected, elements)?;
let source_sha256 = parse_digest(selected.source_sha256)?;
let f32_sha256 = parse_digest(selected.f32_sha256)?;
let section_path = self.staging.0.join(format!("{ordinal:06}.section"));
let job = CandidateEncoding {
candidate,
selected: &selected,
elements,
source_sha256,
};
let job = CandidateEncoding { candidate, selected: &selected, elements, source_sha256 };
let section = self.encode_selected(&job, &section_path)?;
if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 {
return Err(format!("{}: candidate source changed", candidate.name));
@@ -80,26 +74,16 @@ impl Encoder<'_> {
})
}
fn check_geometry(
&self,
candidate: &Candidate,
selected: &CandidateSource,
elements: u64,
) -> Result<(), String> {
let base_record = self
.base_records
.get(candidate.name.as_str())
.ok_or("candidate is missing from base KAR directory")?;
fn check_geometry(&self, candidate: &Candidate, selected: &CandidateSource, elements: u64) -> Result<(), String> {
let base_record =
self.base_records.get(candidate.name.as_str()).ok_or("candidate is missing from base KAR directory")?;
if elements != candidate.elements
|| selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
|| base_record.offset != selected.derived_offset
|| base_record.digest != parse_digest(selected.f32_sha256)?
|| base_record.dimensions != selected.location.dimensions
{
return Err(format!(
"{}: candidate geometry differs from base",
candidate.name
));
return Err(format!("{}: candidate geometry differs from base", candidate.name));
}
Ok(())
}
@@ -109,8 +93,7 @@ impl Encoder<'_> {
job: &CandidateEncoding<'_>,
section_path: &Path,
) -> Result<kar_stream_encode::SectionResult, String> {
let mut source =
File::open(&job.selected.location.path).map_err(|error| error.to_string())?;
let mut source = File::open(&job.selected.location.path).map_err(|error| error.to_string())?;
let calibration = self.fit_calibration(&mut source, job)?;
kar_stream_encode::encode_section(&mut source, job.span(), &calibration, section_path)
}
@@ -120,12 +103,8 @@ impl Encoder<'_> {
source: &mut File,
job: &CandidateEncoding<'_>,
) -> Result<kar_codec::Calibration, String> {
let sample = kar_sample::sample_normalized(
source,
job.span(),
job.source_sha256,
kar_sample::MAX_SAMPLE_VALUES,
)?;
let sample =
kar_sample::sample_normalized(source, job.span(), job.source_sha256, kar_sample::MAX_SAMPLE_VALUES)?;
kar_codec::fit_topdown(&sample, self.candidates.proposed_levels)
.map_err(|error| format!("{}: {error}", job.candidate.name))
}
@@ -150,10 +129,7 @@ impl OverlayIdentity<'_> {
prepared: &[Prepared],
) -> Result<Summary, String> {
let archive = self.write_archive(destination, prepared)?;
let mut pending = PendingArchive {
path: destination.to_path_buf(),
committed: false,
};
let mut pending = PendingArchive { path: destination.to_path_buf(), committed: false };
let archive_sha256 = hash_file(destination)?;
verify_written(destination, &archive, prepared)?;
let hashes = OverlayHashes {
@@ -167,11 +143,7 @@ impl OverlayIdentity<'_> {
Ok(summarize(&archive, archive_sha256, prepared, sidecar))
}
fn write_archive(
&self,
destination: &Path,
prepared: &[Prepared],
) -> Result<kar::Summary, String> {
fn write_archive(&self, destination: &Path, prepared: &[Prepared]) -> Result<kar::Summary, String> {
let tensors = overlay_tensors(prepared, self.levels);
let builder = format!(
"leleka-api/experimental-kar-overlay-v1:l{}:base{}:policy{}",
@@ -215,18 +187,12 @@ fn overlay_tensors(prepared: &[Prepared], levels: u8) -> Vec<kar_writer::Tensor<
.collect()
}
fn verify_written(
destination: &Path,
archive: &kar::Summary,
prepared: &[Prepared],
) -> Result<(), String> {
fn verify_written(destination: &Path, archive: &kar::Summary, prepared: &[Prepared]) -> Result<(), String> {
let (verified, records) = kar::verify_with_sources(destination)?;
if verified != *archive
|| records.len() != prepared.len()
|| records.iter().zip(prepared).any(|(record, entry)| {
record.name != entry.name
|| record.digest != entry.f32_sha256
|| record.offset != entry.source_offset
record.name != entry.name || record.digest != entry.f32_sha256 || record.offset != entry.source_offset
})
{
return Err("overlay archive source records failed verification".into());
@@ -261,20 +227,12 @@ fn provenance_json(hashes: &OverlayHashes, levels: u8, prepared: &[Prepared]) ->
})
}
fn summarize(
archive: &kar::Summary,
archive_sha256: [u8; 32],
prepared: &[Prepared],
sidecar: PathBuf,
) -> Summary {
fn summarize(archive: &kar::Summary, archive_sha256: [u8; 32], prepared: &[Prepared], sidecar: PathBuf) -> Summary {
Summary {
archive_bytes: archive.archive_bytes,
archive_sha256,
record_count: prepared.len(),
maximum_relative_l2: prepared
.iter()
.map(|entry| entry.relative_l2)
.fold(0.0f64, f64::max),
maximum_relative_l2: prepared.iter().map(|entry| entry.relative_l2).fold(0.0f64, f64::max),
provenance_path: sidecar,
}
}
@@ -9,15 +9,12 @@ pub(super) fn sidecar_of(archive: &Path, missing_name: &'static str) -> Result<P
}
pub(super) fn read_json<T: serde::de::DeserializeOwned>(path: PathBuf) -> Result<T, String> {
serde_json::from_reader(File::open(path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())
serde_json::from_reader(File::open(path).map_err(|error| error.to_string())?).map_err(|error| error.to_string())
}
/// The element count of a shape, or `None` on overflow.
pub(super) fn shape_elements(dimensions: &[u64]) -> Option<u64> {
dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
dimensions.iter().try_fold(1u64, |n, dim| n.checked_mul(*dim))
}
/// The F32 byte size of a shape, or `None` on overflow.
@@ -38,11 +35,7 @@ pub(super) fn add_locations(
index: gguf::TensorIndex,
) -> Result<(), String> {
for tensor in index.tensors {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
let absolute = index.summary.data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?;
let location = Location {
path: path.to_path_buf(),
absolute,
@@ -59,8 +52,5 @@ pub(super) fn add_locations(
/// The directory entries of a KAR archive by tensor name.
pub(super) fn index_by_name(sources: &[kar::TensorSource]) -> HashMap<&str, &kar::TensorSource> {
sources
.iter()
.map(|record| (record.name.as_str(), record))
.collect()
sources.iter().map(|record| (record.name.as_str(), record)).collect()
}
+6 -23
View File
@@ -55,19 +55,12 @@ fn plan_sources(
let base_sources = check_base_header(base_archive, base, source_digest)?;
let (locations, architecture) = locate_sources(manifest, source_dir, base)?;
check_unique_base_tensors(base)?;
Ok(SourcePlan {
base_digest,
source_digest,
base_sources,
locations,
architecture,
})
Ok(SourcePlan { base_digest, source_digest, base_sources, locations, architecture })
}
fn read_candidates(candidate_path: &Path) -> Result<(Vec<u8>, Candidates), String> {
let bytes = fs::read(candidate_path).map_err(|error| error.to_string())?;
let candidates: Candidates =
serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
let candidates: Candidates = serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
if candidates.schema != "leleka-api/proposed-kar-precision-candidates-v1"
|| !(1..=8).contains(&candidates.proposed_levels)
|| candidates.records.is_empty()
@@ -80,8 +73,7 @@ fn read_candidates(candidate_path: &Path) -> Result<(Vec<u8>, Candidates), Strin
fn read_base(base_archive: &Path, candidates: &Candidates) -> Result<BaseProvenance, String> {
let base_sidecar = sidecar_of(base_archive, "base archive has no file name")?;
let base: BaseProvenance = read_json(base_sidecar)?;
if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256
{
if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256 {
return Err("candidate policy differs from base KAR provenance".into());
}
Ok(base)
@@ -93,20 +85,14 @@ fn check_base_header(
source_digest: [u8; 32],
) -> Result<Vec<kar::TensorSource>, String> {
let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?;
if base_summary.source_digest != source_digest
|| base_summary.source_bytes != base.derived_f32_bytes
{
if base_summary.source_digest != source_digest || base_summary.source_bytes != base.derived_f32_bytes {
return Err("base KAR header differs from provenance".into());
}
Ok(base_sources)
}
fn check_unique_base_tensors(base: &BaseProvenance) -> Result<(), String> {
let names = base
.tensors
.iter()
.map(|tensor| tensor.name.as_str())
.collect::<HashSet<_>>();
let names = base.tensors.iter().map(|tensor| tensor.name.as_str()).collect::<HashSet<_>>();
if names.len() != base.tensors.len() {
return Err("duplicate tensor in base provenance".into());
}
@@ -138,10 +124,7 @@ fn locate_sources(
Ok((locations, architecture))
}
fn check_shard_identity(
entry: &crate::model::ModelFile,
recorded: &BaseShard,
) -> Result<(), String> {
fn check_shard_identity(entry: &crate::model::ModelFile, recorded: &BaseShard) -> Result<(), String> {
let mut components = Path::new(&entry.name).components();
let plain_name = matches!(components.next(), Some(Component::Normal(_)));
if entry.name != recorded.name
@@ -10,13 +10,10 @@ use super::{
/// Verify both complete archives and bind every replacement to the same
/// virtual-F32 source record before a loader selects an archive by tensor name.
pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result<Resolution, String> {
let base: BaseProvenance =
read_json(sidecar_of(base_archive, "KAR archive has no file name")?)?;
let overlay: OverlayProvenance =
read_json(sidecar_of(overlay_archive, "KAR archive has no file name")?)?;
let base: BaseProvenance = read_json(sidecar_of(base_archive, "KAR archive has no file name")?)?;
let overlay: OverlayProvenance = read_json(sidecar_of(overlay_archive, "KAR archive has no file name")?)?;
check_archives(&base, &overlay, base_archive, overlay_archive)?;
let (base_sources, overlay_sources) =
verify_directories(&base, &overlay, base_archive, overlay_archive)?;
let (base_sources, overlay_sources) = verify_directories(&base, &overlay, base_archive, overlay_archive)?;
check_base_directory(&base, &base_sources)?;
let replacements = overlay_replacements(&overlay, &overlay_sources)?;
let records = resolve_records(&base_sources, &overlay_sources, &replacements)?;
@@ -35,18 +32,13 @@ fn check_archives(
base_archive: &Path,
overlay_archive: &Path,
) -> Result<(), String> {
if policy_differs(base, overlay)
|| archives_differ(base, overlay, base_archive, overlay_archive)?
{
if policy_differs(base, overlay) || archives_differ(base, overlay, base_archive, overlay_archive)? {
return Err("base or overlay archive differs from its provenance".into());
}
Ok(())
}
fn check_base_directory(
base: &BaseProvenance,
base_sources: &[kar::TensorSource],
) -> Result<(), String> {
fn check_base_directory(base: &BaseProvenance, base_sources: &[kar::TensorSource]) -> Result<(), String> {
let expected = expected_sources(base)?;
if expected.len() != base_sources.len() {
return Err("base KAR record count differs from partitioned provenance".into());
@@ -113,9 +105,8 @@ fn expected_sources(base: &BaseProvenance) -> Result<ExpectedSources<'_>, String
let mut expected = HashMap::new();
let mut partitioned = HashSet::new();
for parent in &base.partitioned_tensors {
let original = recorded_base
.get(parent.parent_name.as_str())
.ok_or("partitioned parent absent from base provenance")?;
let original =
recorded_base.get(parent.parent_name.as_str()).ok_or("partitioned parent absent from base provenance")?;
check_parent_shape(parent, original, &mut partitioned)?;
add_parts(parent, original, &mut expected)?;
}
@@ -152,12 +143,9 @@ fn add_parts<'a>(
let mut last_dimension = 0u64;
for part in &parent.parts {
check_part_geometry(part, parent, offset)?;
offset = offset
.checked_add(part.derived_bytes)
.ok_or("partitioned tensor offset overflow")?;
last_dimension = last_dimension
.checked_add(*part.dimensions.last().unwrap())
.ok_or("partitioned tensor shape overflow")?;
offset = offset.checked_add(part.derived_bytes).ok_or("partitioned tensor offset overflow")?;
last_dimension =
last_dimension.checked_add(*part.dimensions.last().unwrap()).ok_or("partitioned tensor shape overflow")?;
let source = ExpectedSource {
offset: part.derived_offset,
bytes: part.derived_bytes,
@@ -171,11 +159,7 @@ fn add_parts<'a>(
check_coverage(parent, original, offset, last_dimension)
}
fn check_part_geometry(
part: &PartitionPart,
parent: &PartitionedTensor,
offset: u64,
) -> Result<(), String> {
fn check_part_geometry(part: &PartitionPart, parent: &PartitionedTensor, offset: u64) -> Result<(), String> {
if part.dimensions.len() != parent.parent_dimensions.len()
|| part.dimensions[..part.dimensions.len() - 1]
!= parent.parent_dimensions[..parent.parent_dimensions.len() - 1]
@@ -194,10 +178,7 @@ fn check_coverage(
last_dimension: u64,
) -> Result<(), String> {
if offset
!= original
.derived_offset
.checked_add(original.derived_bytes)
.ok_or("partitioned parent offset overflow")?
!= original.derived_offset.checked_add(original.derived_bytes).ok_or("partitioned parent offset overflow")?
|| last_dimension != *parent.parent_dimensions.last().unwrap()
{
return Err("partitioned parts do not cover their parent".into());
@@ -218,14 +199,9 @@ fn add_plain<'a>(record: &'a BaseTensor, expected: &mut ExpectedSources<'a>) ->
Ok(())
}
fn check_base_sources(
base_sources: &[kar::TensorSource],
expected: &ExpectedSources<'_>,
) -> Result<(), String> {
fn check_base_sources(base_sources: &[kar::TensorSource], expected: &ExpectedSources<'_>) -> Result<(), String> {
for source in base_sources {
let record = expected
.get(source.name.as_str())
.ok_or("base KAR tensor absent from provenance")?;
let record = expected.get(source.name.as_str()).ok_or("base KAR tensor absent from provenance")?;
if base_mapping_differs(source, record)? {
return Err(format!("{}: base source mapping differs", source.name));
}
@@ -233,16 +209,11 @@ fn check_base_sources(
Ok(())
}
fn base_mapping_differs(
source: &kar::TensorSource,
record: &ExpectedSource<'_>,
) -> Result<bool, String> {
fn base_mapping_differs(source: &kar::TensorSource, record: &ExpectedSource<'_>) -> Result<bool, String> {
Ok(source.digest != parse_digest(record.digest)?
|| source.offset != record.offset
|| source.dtype != 0
|| record
.dimensions
.is_some_and(|dims| source.dimensions != dims)
|| record.dimensions.is_some_and(|dims| source.dimensions != dims)
|| shape_f32_bytes(&source.dimensions) != Some(record.bytes))
}
@@ -258,9 +229,7 @@ fn overlay_replacements<'a>(
.iter()
.find(|record| record.name == source.name)
.ok_or("overlay KAR tensor absent from provenance")?;
if replacements.insert(source.name.as_str(), index).is_some()
|| overlay_mapping_differs(record, source)
{
if replacements.insert(source.name.as_str(), index).is_some() || overlay_mapping_differs(record, source) {
return Err(format!("{}: overlay source mapping differs", source.name));
}
}
@@ -293,11 +262,7 @@ fn resolve_records(
}
records.push(ResolvedRecord {
name: source.name.clone(),
archive: if replacement.is_some() {
"overlay"
} else {
"base"
},
archive: if replacement.is_some() { "overlay" } else { "base" },
archive_index: replacement.unwrap_or(index),
source_offset: source.offset,
source_sha256: hex::encode(source.digest),
@@ -307,18 +272,10 @@ fn resolve_records(
Ok(records)
}
fn check_same_source(
selected: &kar::TensorSource,
source: &kar::TensorSource,
) -> Result<(), String> {
if selected.digest != source.digest
|| selected.offset != source.offset
|| selected.dimensions != source.dimensions
fn check_same_source(selected: &kar::TensorSource, source: &kar::TensorSource) -> Result<(), String> {
if selected.digest != source.digest || selected.offset != source.offset || selected.dimensions != source.dimensions
{
return Err(format!(
"{}: overlay replaces a different source tensor",
source.name
));
return Err(format!("{}: overlay replaces a different source tensor", source.name));
}
Ok(())
}
@@ -4,11 +4,7 @@
use super::{OpenOptions, Path, Write, fs};
pub(super) fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| error.to_string())?;
let mut file = OpenOptions::new().write(true).create_new(true).open(path).map_err(|error| error.to_string())?;
let result = (|| -> Result<(), String> {
serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?;
file.write_all(b"\n").map_err(|error| error.to_string())?;
+2 -1
View File
@@ -8,8 +8,9 @@ use serde::{Deserialize, Serialize};
use crate::{
derived_mixed, gguf, gguf_f32_stream,
kar::{self, VerifiedRangeDecoder},
kar_shard_plan,
model::Manifest,
prepare_preview, kar_shard_plan,
prepare_preview,
};
const SAMPLE_ELEMENTS: u64 = 4096;
+5 -22
View File
@@ -7,25 +7,15 @@ use super::{
previous, sample_records,
};
pub fn analyze(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Report, String> {
let summary =
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive_path, levels)?;
pub fn analyze(manifest: &Manifest, source_dir: &Path, archive_path: &Path, levels: u8) -> Result<Report, String> {
let summary = prepare_preview::verify_sharded_streamed(manifest, source_dir, archive_path, levels)?;
let archive_sha256 = recorded_archive_sha256(archive_path)?;
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
if summary.source_digest != identity.derived_sha256 {
return Err("KAR source digest changed after verification".into());
}
let parts = kar_shard_plan::plan_shards(&identity, source_dir)?;
let source = SourceShards {
dir: source_dir,
identity: &identity,
parts: &parts,
};
let source = SourceShards { dir: source_dir, identity: &identity, parts: &parts };
sample_records(
source,
VerifiedRangeDecoder::open(archive_path)?,
@@ -40,10 +30,7 @@ fn recorded_archive_sha256(archive_path: &Path) -> Result<String, String> {
let provenance: serde_json::Value =
serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?)
.map_err(|error| error.to_string())?;
Ok(provenance["archive_sha256"]
.as_str()
.ok_or("verified provenance has no archive digest")?
.to_owned())
Ok(provenance["archive_sha256"].as_str().ok_or("verified provenance has no archive digest")?.to_owned())
}
/// Reuse a prior full verification of immutable source shards and archive.
@@ -55,11 +42,7 @@ pub fn analyze_previously_verified(
levels: u8,
) -> Result<Report, String> {
let checked = previous::load(manifest, source_dir, archive_path, levels)?;
let source = SourceShards {
dir: source_dir,
identity: &checked.identity,
parts: &checked.parts,
};
let source = SourceShards { dir: source_dir, identity: &checked.identity, parts: &checked.parts };
sample_records(
source,
VerifiedRangeDecoder::open_previously_verified(archive_path)?,
+18 -70
View File
@@ -18,29 +18,17 @@ pub(super) struct Checked {
}
/// Checks the archive and the source shards against the recorded provenance without rehashing payloads.
pub(super) fn load(
manifest: &Manifest,
source_dir: &Path,
archive_path: &Path,
levels: u8,
) -> Result<Checked, String> {
pub(super) fn load(manifest: &Manifest, source_dir: &Path, archive_path: &Path, levels: u8) -> Result<Checked, String> {
let (provenance, sources, derived_sha256) = read_checked(archive_path, levels)?;
let manifest_files = sorted_manifest_files(manifest, &provenance)?;
let identity = recorded_identity(&manifest_files, &provenance, source_dir, derived_sha256)?;
let partitioned = partition_map(&provenance)?;
let parts = rebuild_parts(source_dir, &identity, &partitioned)?;
check_records(&identity, &partitioned, &parts, &sources)?;
Ok(Checked {
provenance,
identity,
parts,
})
Ok(Checked { provenance, identity, parts })
}
fn read_checked(
archive_path: &Path,
levels: u8,
) -> Result<(Provenance, Vec<kar::TensorSource>, [u8; 32]), String> {
fn read_checked(archive_path: &Path, levels: u8) -> Result<(Provenance, Vec<kar::TensorSource>, [u8; 32]), String> {
let provenance = read_provenance(archive_path)?;
check_header(&provenance, levels)?;
let (summary, sources) = kar::inspect_with_sources(archive_path)?;
@@ -53,10 +41,7 @@ fn read_checked(
pub(super) fn provenance_path(archive_path: &Path) -> Result<std::path::PathBuf, String> {
Ok(archive_path.with_file_name(format!(
"{}.provenance.json",
archive_path
.file_name()
.ok_or("KAR archive has no file name")?
.to_string_lossy()
archive_path.file_name().ok_or("KAR archive has no file name")?.to_string_lossy()
)))
}
@@ -103,10 +88,7 @@ pub(super) fn sorted_manifest_files<'a>(
Ok(manifest_files)
}
fn check_recorded_shard(
manifest_file: &ModelFile,
recorded: &ProvenanceShard,
) -> Result<(), String> {
fn check_recorded_shard(manifest_file: &ModelFile, recorded: &ProvenanceShard) -> Result<(), String> {
if manifest_file.name != recorded.name
|| manifest_file.size != recorded.gguf_bytes
|| manifest_file.sha256 != recorded.gguf_sha256
@@ -123,10 +105,7 @@ fn recorded_shard(
) -> Result<derived_mixed::ShardIdentity, String> {
check_recorded_shard(manifest_file, recorded)?;
let path = source_dir.join(&recorded.name);
if File::open(path)
.and_then(|file| file.metadata())
.map_err(|error| error.to_string())?
.len()
if File::open(path).and_then(|file| file.metadata()).map_err(|error| error.to_string())?.len()
!= recorded.gguf_bytes
{
return Err("source shard length changed since prior verification".into());
@@ -163,9 +142,7 @@ pub(super) fn recorded_identity(
tensors: Vec::with_capacity(provenance.tensors.len()),
};
for (manifest_file, recorded) in manifest_files.iter().zip(&provenance.shards) {
identity
.shards
.push(recorded_shard(source_dir, manifest_file, recorded)?);
identity.shards.push(recorded_shard(source_dir, manifest_file, recorded)?);
}
for tensor in &provenance.tensors {
identity.tensors.push(recorded_tensor(tensor)?);
@@ -186,30 +163,18 @@ pub(super) fn partition_map(provenance: &Provenance) -> Result<Partitions<'_>, S
}
fn element_count(dimensions: &[u64], overflow: &'static str) -> Result<u64, String> {
Ok(dimensions
.iter()
.try_fold(1u64, |n, dim| n.checked_mul(*dim))
.ok_or(overflow)?)
Ok(dimensions.iter().try_fold(1u64, |n, dim| n.checked_mul(*dim)).ok_or(overflow)?)
}
fn check_tensor_metadata(
recorded: &derived_mixed::TensorIdentity,
tensor: &gguf::TensorInfo,
) -> Result<(), String> {
fn check_tensor_metadata(recorded: &derived_mixed::TensorIdentity, tensor: &gguf::TensorInfo) -> Result<(), String> {
let elements = element_count(&tensor.dimensions, "GGUF tensor shape overflow")?;
if recorded.name != tensor.name
|| recorded.source_kind != tensor.kind
|| recorded.derived_bytes != elements * 4
{
if recorded.name != tensor.name || recorded.source_kind != tensor.kind || recorded.derived_bytes != elements * 4 {
return Err("GGUF tensor metadata differs from provenance".into());
}
Ok(())
}
fn recorded_part(
tensor: &gguf::TensorInfo,
part: &ProvenancePart,
) -> Result<kar_shard_plan::PartIdentity, String> {
fn recorded_part(tensor: &gguf::TensorInfo, part: &ProvenancePart) -> Result<kar_shard_plan::PartIdentity, String> {
Ok(kar_shard_plan::PartIdentity {
name: part.name.clone(),
parent_name: tensor.name.clone(),
@@ -225,10 +190,7 @@ fn recorded_part(
})
}
fn whole_part(
tensor: &gguf::TensorInfo,
recorded: &derived_mixed::TensorIdentity,
) -> kar_shard_plan::PartIdentity {
fn whole_part(tensor: &gguf::TensorInfo, recorded: &derived_mixed::TensorIdentity) -> kar_shard_plan::PartIdentity {
kar_shard_plan::PartIdentity {
name: tensor.name.clone(),
parent_name: tensor.name.clone(),
@@ -255,11 +217,7 @@ fn part_group(
if split.source_kind != tensor.kind || split.parts.len() < 2 {
return Err("invalid KAR partition metadata".into());
}
split
.parts
.iter()
.map(|part| recorded_part(tensor, part))
.collect::<Result<Vec<_>, String>>()
split.parts.iter().map(|part| recorded_part(tensor, part)).collect::<Result<Vec<_>, String>>()
}
fn check_group_cover(
@@ -277,16 +235,10 @@ fn check_group_cover(
{
return Err("KAR part offsets or shape differ from provenance".into());
}
source_cursor = source_cursor
.checked_add(part.source_bytes)
.ok_or("KAR part source overflow")?;
derived_cursor = derived_cursor
.checked_add(part.derived_bytes)
.ok_or("KAR part derived overflow")?;
source_cursor = source_cursor.checked_add(part.source_bytes).ok_or("KAR part source overflow")?;
derived_cursor = derived_cursor.checked_add(part.derived_bytes).ok_or("KAR part derived overflow")?;
}
if source_cursor != tensor.bytes
|| derived_cursor != recorded.derived_offset + recorded.derived_bytes
{
if source_cursor != tensor.bytes || derived_cursor != recorded.derived_offset + recorded.derived_bytes {
return Err("KAR parts do not cover GGUF parent".into());
}
Ok(())
@@ -299,16 +251,12 @@ fn shard_parts(
partitioned: &Partitions<'_>,
parts: &mut Groups,
) -> Result<(), String> {
let index =
gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?;
let index = gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?;
if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes {
return Err("GGUF shard metadata changed since prior verification".into());
}
for tensor in &index.tensors {
let recorded = identity
.tensors
.get(parts.len())
.ok_or("GGUF tensor count differs from provenance")?;
let recorded = identity.tensors.get(parts.len()).ok_or("GGUF tensor count differs from provenance")?;
check_tensor_metadata(recorded, tensor)?;
let group = part_group(tensor, recorded, partitioned)?;
check_group_cover(&group, tensor, recorded)?;

Some files were not shown because too many files have changed in this diff Show More