diff --git a/control-plane/examples/compare-iq3-s.rs b/control-plane/examples/compare-iq3-s.rs index 1b857aac..65075ee5 100644 --- a/control-plane/examples/compare-iq3-s.rs +++ b/control-plane/examples/compare-iq3-s.rs @@ -10,25 +10,23 @@ use std::{ use strata_control::{ggml_bridge, gguf, iq3_s}; -fn main() -> Result<(), Box> { +type Failure = Box; + +const USAGE: &str = "usage: compare-iq3-s FILE.gguf [BLOCKS]"; + +/// The GGUF path and the number of blocks to compare (1024 by default). +fn parse_args() -> Result<(String, u64), Failure> { let mut args = env::args().skip(1); - let path = args - .next() - .ok_or("usage: compare-iq3-s FILE.gguf [BLOCKS]")?; + let path = args.next().ok_or(USAGE)?; let requested: u64 = args.next().unwrap_or_else(|| "1024".into()).parse()?; if args.next().is_some() || requested == 0 { - return Err("usage: compare-iq3-s FILE.gguf [BLOCKS]".into()); + return Err(USAGE.into()); } - 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 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))?; + Ok((path, requested)) +} + +/// Compares `blocks` consecutive blocks of `source` between the Rust decoder and pinned ggml, bit for bit. +fn compare_blocks(source: &mut File, blocks: u64) -> Result<(), Failure> { let mut block = [0u8; iq3_s::BLOCK_BYTES]; let mut ggml = [0.0f32; iq3_s::BLOCK_ELEMENTS]; for number in 0..blocks { @@ -48,6 +46,22 @@ fn main() -> Result<(), Box> { .into()); } } + Ok(()) +} + +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 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))?; + compare_blocks(&mut source, blocks)?; println!( "{}: {blocks} IQ3_S blocks, {} F32 values bit-identical to pinned ggml", tensor.name, diff --git a/control-plane/examples/compare-kar-range.rs b/control-plane/examples/compare-kar-range.rs index a07054d7..e411825a 100644 --- a/control-plane/examples/compare-kar-range.rs +++ b/control-plane/examples/compare-kar-range.rs @@ -10,29 +10,49 @@ use std::{ use strata_control::{ggml_bridge, gguf, kar}; -fn main() -> Result<(), Box> { +type Failure = Box; + +const USAGE: &str = "usage: compare-kar-range FILE.gguf FILE.kar LEVEL START COUNT"; + +/// The command line: the one-tensor GGUF, the KAR archive, the level and the element range. +struct Args { + source_path: String, + archive_path: String, + level: u8, + start: usize, + count: usize, +} + +fn parse_args() -> Result { let mut args = env::args().skip(1); - let usage = "usage: compare-kar-range FILE.gguf FILE.kar LEVEL START COUNT"; - let source_path = args.next().ok_or(usage)?; - let archive_path = args.next().ok_or(usage)?; - let level: u8 = args.next().ok_or(usage)?.parse()?; - let start: usize = args.next().ok_or(usage)?.parse()?; - let count: usize = args.next().ok_or(usage)?.parse()?; + let source_path = args.next().ok_or(USAGE)?; + let archive_path = args.next().ok_or(USAGE)?; + let level: u8 = args.next().ok_or(USAGE)?.parse()?; + let start: usize = args.next().ok_or(USAGE)?.parse()?; + let count: usize = args.next().ok_or(USAGE)?.parse()?; if args.next().is_some() || count == 0 || count > 1_000_000 { - return Err(usage.into()); + return Err(USAGE.into()); } - let source_path = Path::new(&source_path); - let archive_path = Path::new(&archive_path); - let index = gguf::tensor_index(source_path)?; - if index.tensors.len() != 1 { - return Err("diagnostic source must contain exactly one tensor".into()); + Ok(Args { + source_path, + archive_path, + level, + start, + count, + }) +} + +/// `(elements, bytes)` of one block of the supported source kinds. +fn block_geometry(kind: u32) -> Result<(usize, usize), Failure> { + match kind { + 20 => Ok((32usize, 18usize)), + 21 => Ok((256, 110)), + _ => Err("diagnostic supports IQ4_NL and IQ3_S sources".into()), } - let tensor = &index.tensors[0]; - let (block_elements, block_bytes) = match tensor.kind { - 20 => (32usize, 18usize), - 21 => (256, 110), - _ => return Err("diagnostic supports IQ4_NL and IQ3_S sources".into()), - }; +} + +/// The exclusive end of the range, checked against the element count of the tensor. +fn checked_end(tensor: &gguf::TensorInfo, start: usize, count: usize) -> Result { let end = start.checked_add(count).ok_or("GGUF range overflow")?; let elements = tensor .dimensions @@ -42,48 +62,102 @@ fn main() -> Result<(), Box> { if end > elements { return Err("GGUF range exceeds tensor".into()); } - let reconstructed = kar::decode_tensor_range(archive_path, &tensor.name, level, start, count)?; - let first_block = start / block_elements; - let final_block = end.div_ceil(block_elements); - let first_block_bytes = first_block - .checked_mul(block_bytes) - .and_then(|n| u64::try_from(n).ok()) - .ok_or("GGUF offset overflow")?; - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|n| n.checked_add(first_block_bytes)) - .ok_or("GGUF offset overflow")?; - let mut source = File::open(source_path)?; - source.seek(SeekFrom::Start(absolute))?; + Ok(end) +} + +/// The sums the relative L2 error and the maximum absolute error are made of. +#[derive(Default)] +struct ErrorSums { + error: f64, + reference: f64, + maximum_absolute_error: f64, +} + +impl ErrorSums { + fn add(&mut self, reference: f64, value: f64) { + let error = (reference - value).abs(); + self.error += error * error; + self.reference += reference * reference; + self.maximum_absolute_error = self.maximum_absolute_error.max(error); + } + + fn relative_l2(&self) -> f64 { + if self.reference == 0.0 { + self.error.sqrt() + } else { + (self.error / self.reference).sqrt() + } + } +} + +/// Decodes the GGUF blocks that cover `start..end` and compares them with the archive's `reconstructed` values. +fn compare_blocks( + source: &mut File, + tensor: &gguf::TensorInfo, + (start, end): (usize, usize), + reconstructed: &[f32], +) -> Result { + let (block_elements, block_bytes) = block_geometry(tensor.kind)?; let mut block = vec![0u8; block_bytes]; let mut decoded = vec![0.0f32; block_elements]; - let mut error_sum = 0.0f64; - let mut reference_sum = 0.0f64; - let mut maximum_absolute_error = 0.0f64; - for number in first_block..final_block { + let mut sums = ErrorSums::default(); + for number in start / block_elements..end.div_ceil(block_elements) { source.read_exact(&mut block)?; ggml_bridge::decode_into(tensor.kind, &block, &mut decoded)?; let begin = start.max(number * block_elements); let finish = end.min((number + 1) * block_elements); for position in begin..finish { let reference = f64::from(decoded[position - number * block_elements]); - let value = f64::from(reconstructed[position - start]); - let error = (reference - value).abs(); - error_sum += error * error; - reference_sum += reference * reference; - maximum_absolute_error = maximum_absolute_error.max(error); + sums.add(reference, f64::from(reconstructed[position - start])); } } - let relative_l2 = if reference_sum == 0.0 { - error_sum.sqrt() - } else { - (error_sum / reference_sum).sqrt() - }; + Ok(sums) +} + +/// The absolute file offset of the block that holds element `start`. +fn first_block_offset(index: &gguf::TensorIndex, start: usize) -> Result { + let tensor = &index.tensors[0]; + let (block_elements, block_bytes) = block_geometry(tensor.kind)?; + let first_block_bytes = (start / block_elements) + .checked_mul(block_bytes) + .and_then(|n| u64::try_from(n).ok()) + .ok_or("GGUF offset overflow")?; + Ok(index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|n| n.checked_add(first_block_bytes)) + .ok_or("GGUF offset overflow")?) +} + +fn main() -> Result<(), Failure> { + let args = parse_args()?; + let (start, count, level) = (args.start, args.count, args.level); + let source_path = Path::new(&args.source_path); + let index = gguf::tensor_index(source_path)?; + if index.tensors.len() != 1 { + return Err("diagnostic source must contain exactly one tensor".into()); + } + let tensor = &index.tensors[0]; + block_geometry(tensor.kind)?; + let end = checked_end(tensor, start, count)?; + let archive_path = Path::new(&args.archive_path); + let reconstructed = kar::decode_tensor_range(archive_path, &tensor.name, level, start, count)?; + let absolute = first_block_offset(&index, start)?; + let mut source = File::open(source_path)?; + source.seek(SeekFrom::Start(absolute))?; + let sums = compare_blocks(&mut source, tensor, (start, end), &reconstructed)?; println!( - "{}: {count} archived F32 values decoded at level {level}, start {start}; relative L2 {relative_l2:.8}, maximum absolute error {maximum_absolute_error:.8}", - tensor.name + concat!( + "{}: {} archived F32 values decoded at level {}, start {}; ", + "relative L2 {:.8}, maximum absolute error {:.8}" + ), + tensor.name, + count, + level, + start, + sums.relative_l2(), + sums.maximum_absolute_error ); Ok(()) } diff --git a/control-plane/examples/kar-expert-fixture.rs b/control-plane/examples/kar-expert-fixture.rs index 6c3ae49e..ebf375a5 100644 --- a/control-plane/examples/kar-expert-fixture.rs +++ b/control-plane/examples/kar-expert-fixture.rs @@ -3,21 +3,19 @@ use sha2::{Digest, Sha256}; use std::path::Path; use strata_control::kar_writer::{self, SourceIdentity, Tensor, TensorData}; -fn main() -> Result<(), String> { - let args: Vec<_> = std::env::args().collect(); - if args.len() != 2 { - return Err("usage: kar-expert-fixture NEW_OUTPUT.kar".into()); - } - const H: u64 = 64; - const F: u64 = 32; - const E: u64 = 2; - let scales = vec![0x2800u16; (H * F * E / 32) as usize]; // 1/32 - let mut plane = vec![u32::MAX; (H * F / 32) as usize]; - plane.extend(vec![0u32; (H * F / 32) as usize]); - let book = [0xbc00u16, 0x3c00]; // expert 0 positive, expert 1 negative - let books: [&[u16]; 1] = [&book]; - let planes: [&[u32]; 1] = [&plane]; - let raw: Vec = (0..3) +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", +]; + +/// The three raw F32 tensors: expert 0 is 1/32 everywhere and expert 1 is -1/32. +fn raw_source() -> Vec { + (0..3) .flat_map(|_| { (0..H * F * E).flat_map(|i| { (if i < H * F { @@ -28,41 +26,62 @@ fn main() -> Result<(), String> { .to_le_bytes() }) }) - .collect(); - let source = SourceIdentity { + .collect() +} + +fn source_identity(raw: &[u8]) -> SourceIdentity<'static> { + SourceIdentity { name: "synthetic-routed-experts", architecture: "synthetic", builder: "strata-next/kar-expert-fixture-v1", - digest: Sha256::digest(&raw).into(), + digest: Sha256::digest(raw).into(), total_elements: H * F * E * 3, bytes: raw.len() as u64, - }; + } +} + +/// One routed-expert tensor of `role` (gate, up, down) over the shared scales, book and plane. +fn expert_tensor<'a>( + role: usize, + raw: &[u8], + dims: &'a [u64; 3], + nested: (&'a [u16], &'a [&'a [u16]], &'a [&'a [u32]]), +) -> Tensor<'a> { + let (scales, books, planes) = nested; + Tensor { + name: NAMES[role], + dims, + 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, + }, + } +} + +fn main() -> Result<(), String> { + let args: Vec<_> = std::env::args().collect(); + if args.len() != 2 { + return Err("usage: kar-expert-fixture NEW_OUTPUT.kar".into()); + } + let scales = vec![0x2800u16; (H * F * E / 32) as usize]; // 1/32 + let mut plane = vec![u32::MAX; (H * F / 32) as usize]; + plane.extend(vec![0u32; (H * F / 32) as usize]); + let book = [0xbc00u16, 0x3c00]; // expert 0 positive, expert 1 negative + let books: [&[u16]; 1] = [&book]; + let planes: [&[u32]; 1] = [&plane]; + let raw = raw_source(); + let source = source_identity(&raw); let dims = [[H, F, E], [H, F, E], [F, H, E]]; - let names = [ - "blk.0.ffn_gate_exps.weight", - "blk.0.ffn_up_exps.weight", - "blk.0.ffn_down_exps.weight", - ]; let tensors: Vec<_> = (0..3) - .map(|role| Tensor { - name: names[role], - dims: &dims[role], - source_dtype: 0, - source_digest: Sha256::digest( - &raw[role * (H * F * E * 4) as usize..(role + 1) * (H * F * E * 4) as usize], - ) - .into(), - source_offset: role as u64 * H * F * E * 4, - data: TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: 1, - scales: &scales, - books: &books, - planes: &planes, - }, - }) + .map(|role| expert_tensor(role, &raw, &dims[role], (&scales, &books, &planes))) .collect(); kar_writer::write_archive(Path::new(&args[1]), &source, &tensors)?; Ok(()) diff --git a/control-plane/examples/scan-quant-blocks.rs b/control-plane/examples/scan-quant-blocks.rs index 597d0df7..c6a0c577 100644 --- a/control-plane/examples/scan-quant-blocks.rs +++ b/control-plane/examples/scan-quant-blocks.rs @@ -6,7 +6,48 @@ use std::{collections::BTreeMap, env, fs::File, path::Path}; use sha2::{Digest, Sha256}; use strata_control::{gguf, gguf_f32_stream}; -fn main() -> Result<(), Box> { +type Failure = Box; + +fn all_finite(values: &[u8]) -> bool { + 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> { + 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 mut hasher = Sha256::new(); + let decoded_bytes = gguf_f32_stream::visit(source, absolute, kind, bytes, |_, values| { + if !all_finite(values) { + return Err(format!("{}: non-finite decoded value", tensor.name)); + } + hasher.update(values); + Ok(()) + })?; + if decoded_bytes != expected_elements * 4 { + return Err(format!("{}: decoded block length mismatch", tensor.name).into()); + } + println!( + "kind {kind}: {} values from {} SHA-256 {}", + expected_elements, + tensor.name, + hex::encode(hasher.finalize()) + ); + Ok(()) +} + +fn main() -> Result<(), Failure> { let path = env::args() .nth(1) .ok_or("usage: scan-quant-blocks FILE.gguf")?; @@ -18,36 +59,7 @@ fn main() -> Result<(), Box> { } let mut source = File::open(path)?; for (kind, tensor) in first_by_kind { - let (expected_elements, bytes) = - gguf::block_geometry(kind).ok_or_else(|| format!("unsupported source kind {kind}"))?; - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - let mut hasher = Sha256::new(); - let decoded_bytes = - gguf_f32_stream::visit(&mut source, absolute, kind, bytes, |_, values| { - if values - .as_chunks::<4>() - .0 - .iter() - .any(|word| !f32::from_le_bytes(*word).is_finite()) - { - return Err(format!("{}: non-finite decoded value", tensor.name)); - } - hasher.update(values); - Ok(()) - })?; - if decoded_bytes != expected_elements * 4 { - return Err(format!("{}: decoded block length mismatch", tensor.name).into()); - } - println!( - "kind {kind}: {} values from {} SHA-256 {}", - expected_elements, - tensor.name, - hex::encode(hasher.finalize()) - ); + scan_kind(&mut source, index.summary.data_start, (kind, tensor))?; } Ok(()) } diff --git a/control-plane/tests/backend_worker_http/text_answers.rs b/control-plane/tests/backend_worker_http/text_answers.rs index c5e0bef3..298c469f 100644 --- a/control-plane/tests/backend_worker_http/text_answers.rs +++ b/control-plane/tests/backend_worker_http/text_answers.rs @@ -128,11 +128,7 @@ async fn assert_length_finish_is_incomplete(stack: &Stack) { ); } -#[tokio::test] -async fn length_finish_is_incomplete_and_tool_calls_reason_is_a_stop() { - let stack = Stack::start("bw-length").await; - assert_length_finish_is_incomplete(&stack).await; - +async fn assert_length_stream_is_incomplete(stack: &Stack) { stack.engine.push(Script::finishing( &["cut"], FinishReason::Length, @@ -147,6 +143,14 @@ async fn length_finish_is_incomplete_and_tool_calls_reason_is_a_stop() { let events = sse_events(&text); assert_stream_invariants(&events); assert_eq!(events.last().unwrap()["type"], "response.incomplete"); +} + +#[tokio::test] +async fn length_finish_is_incomplete_and_tool_calls_reason_is_a_stop() { + let stack = Stack::start("bw-length").await; + assert_length_finish_is_incomplete(&stack).await; + + assert_length_stream_is_incomplete(&stack).await; // `tool_calls` from an engine carries no native calls here: tool calls come from the text. stack.engine.push(Script::finishing( diff --git a/control-plane/tests/fixtures/scripted_engine.rs b/control-plane/tests/fixtures/scripted_engine.rs index 95a5f831..eb2aaaa4 100644 --- a/control-plane/tests/fixtures/scripted_engine.rs +++ b/control-plane/tests/fixtures/scripted_engine.rs @@ -66,6 +66,14 @@ fn play_stream( (sent, finish) } +/// The ids of the `call`-th script line. +fn script_stream(script: &[String], call: usize) -> Vec { + script + .get(call) + .map(|l| l.split(',').filter_map(|s| s.parse().ok()).collect()) + .unwrap_or_default() +} + fn main() { let args: Vec = std::env::args().collect(); let dir = std::path::PathBuf::from(&args[2]); @@ -88,10 +96,7 @@ fn main() { let max_new: usize = fields[1].parse().unwrap(); let prompt = fields.last().unwrap(); log_request(&dir, max_new, prompt); - let stream: Vec = script - .get(call) - .map(|l| l.split(',').filter_map(|s| s.parse().ok()).collect()) - .unwrap_or_default(); + let stream = script_stream(&script, call); call += 1; let (sent, finish) = play_stream(&mut out, &lines, (&stream, max_new), &stops); let prompt_tokens = prompt.split(',').filter(|s| !s.is_empty()).count(); diff --git a/control-plane/tests/reasoning_budget_oracle.rs b/control-plane/tests/reasoning_budget_oracle.rs index 60f94eb6..c07352ac 100644 --- a/control-plane/tests/reasoning_budget_oracle.rs +++ b/control-plane/tests/reasoning_budget_oracle.rs @@ -130,6 +130,14 @@ fn budget_lookup_matches_python() { } } +fn finish_name(finish: &Finish) -> &'static str { + match finish { + Finish::Length => "length", + Finish::Stop => "stop", + Finish::Cancel => "cancel", + } +} + /// Plays one recorded run against the port and compares the engine calls, finish, tokens and text; /// true when the run wrapped up. fn replay_case(codec: &Codec, stops: &HashSet, case: &RunCase, index: usize) -> bool { @@ -151,11 +159,7 @@ fn replay_case(codec: &Codec, stops: &HashSet, case: &RunCase, index: usize }; let cancel = case.cancel; let got = run(&mut engine, codec, &request, &move || cancel).unwrap(); - let finish = match got.finish { - Finish::Length => "length", - Finish::Stop => "stop", - Finish::Cancel => "cancel", - }; + let finish = finish_name(&got.finish); assert_eq!( engine.calls, case.expect.calls, "case {index}: engine calls"