From 9431242e55dfa2d2cb169afce6ef9aa0a61dbd84 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 09:32:13 +0100 Subject: [PATCH] STRA-338 size4-e: engine/leaf crates within the 301 limits gemm shader generator split (template + unrolled parts, output verified byte-identical for all kinds/tiles/moe), OpenVino::load split into per-group loaders, long string literals and comments wrapped; baseline and allowlist tightened. Co-Authored-By: Claude Sonnet 5.5 --- crates/experimental-ref/src/cache.rs | 3 +- .../src/prompt/without_empty_turns.rs | 4 +- .../src/tool_output/impl_incremental.rs | 4 +- crates/gguf/src/inventory.rs | 6 +- crates/gptoss-igpu/src/lib.rs | 7 +- crates/gptoss-npu/src/accelerator.rs | 3 +- crates/gptoss-npu/src/lib.rs | 4 +- crates/gptoss/src/profile.rs | 3 +- crates/gpu-npu-worker/src/lib.rs | 3 +- crates/gpu-npu-worker/src/main.rs | 5 +- crates/igpu-worker/src/main.rs | 3 +- crates/igpu/src/shaders.rs | 1 + crates/igpu/src/shaders/gemm.rs | 316 ++++++++++-------- crates/igpu/src/shaders/gemm_template.rs | 94 ++++++ crates/npu-service/src/engine/impl_engine.rs | 3 +- crates/npu-worker/src/main.rs | 4 +- crates/openvino/src/c_api_types.rs | 31 ++ crates/openvino/src/compile_and_infer.rs | 32 +- crates/openvino/src/lib.rs | 2 +- crates/openvino/src/library.rs | 198 ++++++----- crates/openvino/src/tensor.rs | 12 +- crates/serving-policy/src/watchdog.rs | 3 +- limits-allowlist.json | 30 -- limits-baseline.json | 35 +- 24 files changed, 484 insertions(+), 322 deletions(-) create mode 100644 crates/igpu/src/shaders/gemm_template.rs diff --git a/crates/experimental-ref/src/cache.rs b/crates/experimental-ref/src/cache.rs index 1b7b9dfb..89fb8feb 100644 --- a/crates/experimental-ref/src/cache.rs +++ b/crates/experimental-ref/src/cache.rs @@ -262,7 +262,8 @@ pub fn append_cell( append_q8_half(&mut pools.v_q, &mut pools.v_scale, hv, table, pos, v, s) } KvFormat::K8V4 => { - // layer.cpp: fwht256(vcur); kv_append_q8_step(k_q, k_q, ..., kcur, kcur); kv_append_q4_step(v_q4, v_q4, ..., vcur, vcur) + // layer.cpp: fwht256(vcur); kv_append_q8_step(k_q, k_q, ..., kcur, kcur); + // kv_append_q4_step(v_q4, v_q4, ..., vcur, vcur) // mode 0 only: no host mirror ("K8V4 does not support streaming") append_q8_half(&mut pools.k_q, &mut pools.k_scale, None, table, pos, k, s)?; append_q4_half(&mut pools.v_q4, None, table, pos, v, s, c) diff --git a/crates/gateway-text/src/prompt/without_empty_turns.rs b/crates/gateway-text/src/prompt/without_empty_turns.rs index 510f1e35..4bc13cfe 100644 --- a/crates/gateway-text/src/prompt/without_empty_turns.rs +++ b/crates/gateway-text/src/prompt/without_empty_turns.rs @@ -24,8 +24,8 @@ pub fn render_with_images( if messages.is_empty() { return Err("prompt needs a message".into()); } - // The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below and the native - // renderer work on the same list. + // The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below + // and the native renderer work on the same list. let kept = without_empty_turns(messages); let messages = kept.as_slice(); let first_non_system = messages diff --git a/crates/gateway-text/src/tool_output/impl_incremental.rs b/crates/gateway-text/src/tool_output/impl_incremental.rs index 0df02204..17127b40 100644 --- a/crates/gateway-text/src/tool_output/impl_incremental.rs +++ b/crates/gateway-text/src/tool_output/impl_incremental.rs @@ -53,8 +53,8 @@ impl<'a> Incremental<'a> { while let Some(relative) = self.buffer[search..].find("") { let end = search + relative + "".len(); let mut found = Notes::default(); - // A `` left out is not accepted while streaming: the `` found may be text inside a value, and - // only the end of the generation can tell (see `finish_after`). + // A `` left out is not accepted while streaming: the `` found may be text inside a + // value, and only the end of the generation can tell (see `finish_after`). if let Ok((calls, used)) = read_wrapped( &self.buffer[..end], self.tools, diff --git a/crates/gguf/src/inventory.rs b/crates/gguf/src/inventory.rs index f3262f3d..ddb8a0ca 100644 --- a/crates/gguf/src/inventory.rs +++ b/crates/gguf/src/inventory.rs @@ -294,7 +294,11 @@ fn per_token_bytes( match (expert_count, used) { (Some(total), Some(used)) if total > 0 && used <= total => { if t.dims.last() != Some(&total) { - notes.push(format!("{}: last dimension {:?} is not the expert count {total}; counted in full", t.name, t.dims.last())); + notes.push(format!( + "{}: last dimension {:?} is not the expert count {total}; counted in full", + t.name, + t.dims.last() + )); return t.bytes as f64; } t.bytes as f64 * used as f64 / total as f64 diff --git a/crates/gptoss-igpu/src/lib.rs b/crates/gptoss-igpu/src/lib.rs index 611af8bc..3205c38a 100644 --- a/crates/gptoss-igpu/src/lib.rs +++ b/crates/gptoss-igpu/src/lib.rs @@ -226,7 +226,9 @@ impl GpuPrefill { Ok(()) } else { Err(ModelError::Unsupported( - "the GPU prefill is written for head dimension 64, 8 query heads per KV head and 32 experts with 4 used".into(), + "the GPU prefill is written for head dimension 64, 8 query heads per KV head and 32 experts \ + with 4 used" + .into(), )) } } @@ -278,7 +280,8 @@ impl PrefillAccelerator for GpuPrefill { if !admitted { self.refused += 1; eprintln!( - "leleka-gptoss-igpu: GPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU for this prompt", + "leleka-gptoss-igpu: GPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; \ + using the CPU for this prompt", needed >> 20, available >> 20 ); diff --git a/crates/gptoss-npu/src/accelerator.rs b/crates/gptoss-npu/src/accelerator.rs index 3f0812a6..5fd22cb3 100644 --- a/crates/gptoss-npu/src/accelerator.rs +++ b/crates/gptoss-npu/src/accelerator.rs @@ -26,7 +26,8 @@ impl PrefillAccelerator for NpuPrefill { let admitted = available >= needed; if !admitted { eprintln!( - "leleka-gptoss-npu: NPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU for this prompt", + "leleka-gptoss-npu: NPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; \ + using the CPU for this prompt", needed >> 20, available >> 20 ); diff --git a/crates/gptoss-npu/src/lib.rs b/crates/gptoss-npu/src/lib.rs index a7e9ab8f..c61b0f4c 100644 --- a/crates/gptoss-npu/src/lib.rs +++ b/crates/gptoss-npu/src/lib.rs @@ -58,7 +58,9 @@ impl Timings { pub fn report(&self) -> String { let s = |d: Duration| d.as_secs_f64(); format!( - "{} tokens in {:.2} s: npu {:.2} | cpu attention {:.2} | cpu other {:.2} (norm+upload {:.2}, qkv to caches {:.2}, attention upload {:.2}, residual+router {:.2}, residual add {:.2}, expert gather {:.2}, expert activation {:.2}, expert combine {:.2})", + "{} tokens in {:.2} s: npu {:.2} | cpu attention {:.2} | cpu other {:.2} (norm+upload {:.2}, \ + qkv to caches {:.2}, attention upload {:.2}, residual+router {:.2}, residual add {:.2}, \ + expert gather {:.2}, expert activation {:.2}, expert combine {:.2})", self.tokens, s(self.total), s(self.npu), diff --git a/crates/gptoss/src/profile.rs b/crates/gptoss/src/profile.rs index be825fe7..36e6eac1 100644 --- a/crates/gptoss/src/profile.rs +++ b/crates/gptoss/src/profile.rs @@ -35,7 +35,8 @@ impl Profile { + ms(self.down_region) + ms(self.lm_head); format!( - "per token ms: qkv {:.1} | attention {:.1} | o-proj {:.1} | router {:.1} | gate+up {:.1} | activation {:.1} | down {:.1} | lm-head {:.1} | total {:.1}", + "per token ms: qkv {:.1} | attention {:.1} | o-proj {:.1} | router {:.1} | gate+up {:.1} | \ + activation {:.1} | down {:.1} | lm-head {:.1} | total {:.1}", ms(self.qkv_region), ms(self.attention), ms(self.o_region), diff --git a/crates/gpu-npu-worker/src/lib.rs b/crates/gpu-npu-worker/src/lib.rs index 4441ad3b..ddbca490 100644 --- a/crates/gpu-npu-worker/src/lib.rs +++ b/crates/gpu-npu-worker/src/lib.rs @@ -310,7 +310,8 @@ impl PrefillAccelerator for GpuNpuPrefill { let admitted = available >= needed; if !admitted { eprintln!( - "leleka-gpu-npu: prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU for this prompt", + "leleka-gpu-npu: prefill of {tokens} tokens needs about {} MiB and {} MiB are \ + available; using the CPU for this prompt", needed >> 20, available >> 20 ); diff --git a/crates/gpu-npu-worker/src/main.rs b/crates/gpu-npu-worker/src/main.rs index f1c3bc05..b525e126 100644 --- a/crates/gpu-npu-worker/src/main.rs +++ b/crates/gpu-npu-worker/src/main.rs @@ -43,7 +43,10 @@ struct Args { } fn usage() -> &'static str { - "usage: leleka-gpu-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" + "usage: leleka-gpu-npu-worker --serve --model --openvino-root \ + [--npu-service ] [--npu-device NPU] [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch \ + N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] [--no-warm] [--seed N] \ + [--speculate] [--cache-slots N]" } /// The options as they are read, before the required ones are checked. diff --git a/crates/igpu-worker/src/main.rs b/crates/igpu-worker/src/main.rs index 54597a6a..a95cce09 100644 --- a/crates/igpu-worker/src/main.rs +++ b/crates/igpu-worker/src/main.rs @@ -30,7 +30,8 @@ struct Args { } fn usage() -> &'static str { - "usage: leleka-igpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--gpu-min-tokens N] [--gpu-batch N] [--speculate] [--cache-slots N]" + "usage: leleka-igpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] \ + [--seed N] [--gpu-min-tokens N] [--gpu-batch N] [--speculate] [--cache-slots N]" } /// The options as they are read, before the required ones are checked. diff --git a/crates/igpu/src/shaders.rs b/crates/igpu/src/shaders.rs index 364ab724..3e1da441 100644 --- a/crates/igpu/src/shaders.rs +++ b/crates/igpu/src/shaders.rs @@ -7,6 +7,7 @@ use crate::WeightKind; mod gemm; +mod gemm_template; #[allow(unused_imports)] pub use gemm::*; diff --git a/crates/igpu/src/shaders/gemm.rs b/crates/igpu/src/shaders/gemm.rs index 0ead0ab7..de5a33e5 100644 --- a/crates/igpu/src/shaders/gemm.rs +++ b/crates/igpu/src/shaders/gemm.rs @@ -2,7 +2,7 @@ #[allow(unused_imports)] use super::*; - +use super::gemm_template::TEMPLATE; /// `C[m][n] = sum over blocks of f32(sum of int8 products) * act_scale * weight_scale`. /// @@ -21,62 +21,155 @@ pub fn gemm(kind: WeightKind, tm: u32, tn: u32, moe: bool) -> String { }; let bm = 8 * tm; let bn = 8 * tn; - let mut declare_acc = String::new(); - let mut declare_sum = String::new(); - let mut operands = String::new(); - let mut multiply = String::new(); - let mut scale = String::new(); - let mut store = String::new(); - for i in 0..tm { + let numbers = [ + ("nbk", nbk), + ("ta", bm * 8 * nbk), + ("tb", bn * 8 * nbk), + ("sam", bm * nbk), + ("swn", bn * nbk), + ("bm", bm), + ("bn", bn), + ("tm", tm), + ("tn", tn), + ("loads_a", bm * 8 / 64), + ("loads_b", bn * 8 / 64), + ]; + let mut holes: Vec<(&str, String)> = numbers.iter().map(|(name, n)| (*name, n.to_string())).collect(); + holes.extend(weight_holes(kind)); + holes.extend(row_source_holes(moe)); + holes.extend(Unrolled::new(tm, tn).holes()); + fill(TEMPLATE, &holes) +} + +/// The generated parts that write every accumulator and operand as a named scalar. +struct Unrolled { + declare_acc: String, + declare_sum: String, + operands: String, + multiply: String, + scales: String, + scale: String, + store: String, +} + +impl Unrolled { + fn new(tm: u32, tn: u32) -> Self { + let mut unrolled = Self { + declare_acc: String::new(), + declare_sum: String::new(), + operands: String::new(), + multiply: String::new(), + scales: String::new(), + scale: String::new(), + store: String::new(), + }; + for i in 0..tm { + for j in 0..tn { + unrolled.cell(tm, tn, i, j); + } + } + unrolled.operands_and_scales(tm, tn); + unrolled + } + + /// The accumulator `(i, j)`: its declarations, products, scaling and store. + fn cell(&mut self, tm: u32, tn: u32, i: u32, j: u32) { + self.declare_acc += &format!(" var acc_{i}_{j} = 0.0;\n"); + self.declare_sum += &format!(" var s_{i}_{j} = 0;\n"); + self.multiply += &format!(" s_{i}_{j} += dot4I8Packed(a{i}, b{j});\n"); + self.scale += &format!(" acc_{i}_{j} += f32(s_{i}_{j}) * (sa{i} * sw{j});\n"); + self.store += &store_cell(tm, tn, i, j); + } + + /// The operand reads of one step and the scale reads of one block. + fn operands_and_scales(&mut self, tm: u32, tn: u32) { + for i in 0..tm { + self.operands += &format!(" let a{i} = tile_a[(sub * 8u + kk) * BM + {i}u * 8u + ty];\n"); + } for j in 0..tn { - declare_acc += &format!(" var acc_{i}_{j} = 0.0;\n"); - declare_sum += &format!(" var s_{i}_{j} = 0;\n"); - multiply += &format!(" s_{i}_{j} += dot4I8Packed(a{i}, b{j});\n"); - scale += &format!(" acc_{i}_{j} += f32(s_{i}_{j}) * (sa{i} * sw{j});\n"); - store += &format!( - " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < rows_valid && cc < dims.n) {{ var v = acc_{i}_{j}; if ((dims.flags & 1u) != 0u) {{ v += bias[wbase + cc]; }} if ((dims.flags & 2u) != 0u) {{ v += c[(out_base + r) * dims.n + cc]; }} c[(out_base + r) * dims.n + cc] = v; }} }}\n" - ); + self.operands += &format!(" let b{j} = tile_b[(sub * 8u + kk) * BN + {j}u * 8u + tx];\n"); + } + for i in 0..tm { + self.scales += &format!(" let sa{i} = sa_tile[sub * BM + ty * {tm}u + {i}u];\n"); + } + for j in 0..tn { + self.scales += &format!(" let sw{j} = sw_tile[sub * BN + tx * {tn}u + {j}u];\n"); } } - for i in 0..tm { - operands += - &format!(" let a{i} = tile_a[(sub * 8u + kk) * BM + {i}u * 8u + ty];\n"); + + fn holes(self) -> [(&'static str, String); 7] { + [ + ("declare_acc", self.declare_acc), + ("declare_sum", self.declare_sum), + ("operands", self.operands), + ("multiply", self.multiply), + ("scales", self.scales), + ("scale", self.scale), + ("store", self.store), + ] } - for j in 0..tn { - operands += - &format!(" let b{j} = tile_b[(sub * 8u + kk) * BN + {j}u * 8u + tx];\n"); - } - let mut scales = String::new(); - for i in 0..tm { - scales += &format!(" let sa{i} = sa_tile[sub * BM + ty * {tm}u + {i}u];\n"); - } - for j in 0..tn { - scales += &format!(" let sw{j} = sw_tile[sub * BN + tx * {tn}u + {j}u];\n"); - } - let loads_a = bm * 8 / 64; - let loads_b = bn * 8 / 64; - let (weight_word, weight_scale) = match kind { - WeightKind::Q8_0 => ( - // eight int8 words per block, read as they are - "wq[(wbase + col0 + r) * dims.nb * 8u + kb * 8u + w]".to_owned(), - // half float: two scales per word - "let s = (wbase + col0 + r) * dims.nb + kb; let word = ws[s / 2u]; let pair = unpack2x16float(word); sw_tile[sub * BN + r] = select(pair.x, pair.y, (s & 1u) == 1u);".to_owned(), +} + +/// The guarded store of accumulator `(i, j)`, with the optional bias and the optional add to the existing output. +fn store_cell(tm: u32, tn: u32, i: u32, j: u32) -> String { + format!( + concat!( + " {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; ", + "if (r < rows_valid && cc < dims.n) {{ var v = acc_{i}_{j}; ", + "if ((dims.flags & 1u) != 0u) {{ v += bias[wbase + cc]; }} ", + "if ((dims.flags & 2u) != 0u) {{ v += c[(out_base + r) * dims.n + cc]; }} ", + "c[(out_base + r) * dims.n + cc] = v; }} }}\n" ), + tm = tm, + tn = tn, + i = i, + j = j, + ) +} + +/// The word of the weight tile to read (`weight_word`) and the statement that stores the block scale +/// (`weight_scale`), for the weight format. +fn weight_holes(kind: WeightKind) -> [(&'static str, String); 2] { + let (word, scale) = match kind { + // eight int8 words per block, read as they are; the scale is a half float, two per word + WeightKind::Q8_0 => ( + "wq[(wbase + col0 + r) * dims.nb * 8u + kb * 8u + w]", + concat!( + "let s = (wbase + col0 + r) * dims.nb + kb; let word = ws[s / 2u]; ", + "let pair = unpack2x16float(word); ", + "sw_tile[sub * BN + r] = select(pair.x, pair.y, (s & 1u) == 1u);" + ), + ), + // output word w: elements 4w..4w+3; words 0..3 take the low nibbles of nibble word w, words + // 4..7 the high nibbles of nibble word w - 4 WeightKind::Mxfp4 => ( - // output word w: elements 4w..4w+3; words 0..3 take the low nibbles of nibble word w, words - // 4..7 the high nibbles of nibble word w - 4 - "decode_mxfp4(wq[((wbase + col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)".to_owned(), - "let s = (wbase + col0 + r) * dims.nb + kb; let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; sw_tile[sub * BN + r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));".to_owned(), + "decode_mxfp4(wq[((wbase + col0 + r) * dims.nb + kb) * 4u + (w & 3u)], w >= 4u)", + concat!( + "let s = (wbase + col0 + r) * dims.nb + kb; ", + "let e = (ws[s / 4u] >> (8u * (s & 3u))) & 255u; ", + "sw_tile[sub * BN + r] = bitcast(select(0x00200000u << e, (e - 1u) << 23u, e >= 2u));" + ), ), }; - // Plain products tile the activation rows by workgroup row. The grouped (mixture-of-experts) variant - // takes its tile from a table: the expert, the first compact row and the row count; the weight rows - // start at `expert * n`, the activation row of compact row `i` is `rowmap[i]` (or `i` itself when - // flag 4 is clear), and the output is the compact `[entries][n]` array. + [("weight_word", word.to_owned()), ("weight_scale", scale.to_owned())] +} + +/// Plain products tile the activation rows by workgroup row. The grouped (mixture-of-experts) variant +/// takes its tile from a table: the expert, the first compact row and the row count; the weight rows +/// start at `expert * n`, the activation row of compact row `i` is `rowmap[i]` (or `i` itself when +/// flag 4 is clear), and the output is the compact `[entries][n]` array. +fn row_source_holes(moe: bool) -> [(&'static str, String); 3] { let (extra_bindings, setup, a_row) = if moe { ( - "@group(0) @binding(7) var tiles: array;\n@group(0) @binding(8) var rowmap: array;", - " let tile_at = wid.y * 4u;\n let expert = tiles[tile_at];\n let start = tiles[tile_at + 1u];\n let rows_valid = tiles[tile_at + 2u];\n let row0 = 0u;\n let wbase = expert * dims.n;\n let out_base = start;", + concat!( + "@group(0) @binding(7) var tiles: array;\n", + "@group(0) @binding(8) var rowmap: array;" + ), + concat!( + " let tile_at = wid.y * 4u;\n let expert = tiles[tile_at];\n", + " let start = tiles[tile_at + 1u];\n let rows_valid = tiles[tile_at + 2u];\n", + " let row0 = 0u;\n let wbase = expert * dims.n;\n let out_base = start;" + ), "select(start + r, rowmap[start + r], (dims.flags & 4u) != 0u)", ) } else { @@ -86,105 +179,40 @@ pub fn gemm(kind: WeightKind, tm: u32, tn: u32, moe: bool) -> String { "(row0 + r)", ) }; - format!( - r#" -requires packed_4x8_integer_dot_product; + [ + ("extra_bindings", extra_bindings.to_owned()), + ("setup", setup.to_owned()), + ("a_row", a_row.to_owned()), + ] +} -struct Dims {{ m: u32, n: u32, nb: u32, flags: u32 }} // flags: 1 adds bias[n], 2 adds the existing output -@group(0) @binding(0) var dims: Dims; -@group(0) @binding(1) var wq: array; -@group(0) @binding(2) var ws: array; -@group(0) @binding(3) var aq: array; -@group(0) @binding(4) var asc: array; -@group(0) @binding(5) var c: array; -@group(0) @binding(6) var bias: array; -{extra_bindings} +/// `template` with every `{name}` that names a hole replaced by its text; any other brace is WGSL and stays. +fn fill(template: &str, holes: &[(&str, String)]) -> String { + let mut out = String::with_capacity(template.len() * 2); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let tail = &rest[open + 1..]; + match hole_at(tail, holes) { + Some((close, text)) => { + out.push_str(text); + rest = &tail[close + 1..]; + } + None => { + out.push('{'); + rest = tail; + } + } + } + out.push_str(rest); + out +} -const BM: u32 = {bm}u; -const BN: u32 = {bn}u; -const NBK: u32 = {nbk}u; - -var tile_a: array; // NBK blocks -var tile_b: array; -var sa_tile: array; -var sw_tile: array; - -// the MXFP4 value table (twice the E2M1 value) as magnitudes packed one per nibble: 0 1 2 3 4 6 8 12 -fn mxfp4_magnitude(nibble: u32) -> i32 {{ - return i32((0xC8643210u >> (4u * (nibble & 7u))) & 15u); -}} - -// four nibbles (taken from the low or the high half of each byte of `word`) as four packed int8 values -fn decode_mxfp4(word: u32, high: bool) -> u32 {{ - var out = 0u; - for (var t = 0u; t < 4u; t++) {{ - let byte = (word >> (8u * t)) & 255u; - let nibble = select(byte & 15u, byte >> 4u, high); - let magnitude = mxfp4_magnitude(nibble); - let value = select(magnitude, -magnitude, nibble >= 8u); - out |= (u32(value) & 255u) << (8u * t); - }} - return out; -}} - -@compute @workgroup_size(8, 8) -fn main(@builtin(local_invocation_id) lid: vec3, - @builtin(workgroup_id) wid: vec3) {{ - let tx = lid.x; - let ty = lid.y; - let flat = ty * 8u + tx; -{setup} - let col0 = wid.x * BN; -{declare_acc} - for (var kb0 = 0u; kb0 < dims.nb; kb0 += NBK) {{ - for (var sub = 0u; sub < NBK; sub++) {{ - let kb = kb0 + sub; - let live = kb < dims.nb; - for (var i = 0u; i < {loads_a}u; i++) {{ - let idx = flat + i * 64u; - let r = idx / 8u; - let w = idx % 8u; - var v = 0u; - if (live && row0 + r < rows_valid) {{ v = aq[{a_row} * dims.nb * 8u + kb * 8u + w]; }} - tile_a[(sub * 8u + w) * BM + (r % {tm}u) * 8u + r / {tm}u] = v; - }} - for (var i = 0u; i < {loads_b}u; i++) {{ - let idx = flat + i * 64u; - let r = idx / 8u; - let w = idx % 8u; - var v = 0u; - if (live && col0 + r < dims.n) {{ v = {weight_word}; }} - tile_b[(sub * 8u + w) * BN + (r % {tn}u) * 8u + r / {tn}u] = v; - }} - if (flat < BM) {{ - var v = 0.0; - if (live && row0 + flat < rows_valid) {{ let r = flat; v = asc[{a_row} * dims.nb + kb]; }} - sa_tile[sub * BM + flat] = v; - }} - if (flat < BN) {{ - let r = flat; - sw_tile[sub * BN + r] = 0.0; - if (live && col0 + r < dims.n) {{ {weight_scale} }} - }} - }} - workgroupBarrier(); - for (var sub = 0u; sub < NBK; sub++) {{ -{declare_sum} for (var kk = 0u; kk < 8u; kk++) {{ -{operands}{multiply} }} -{scales}{scale} }} - workgroupBarrier(); - }} -{store}}} -"#, - nbk = nbk, - ta = bm * 8 * nbk, - tb = bn * 8 * nbk, - sam = bm * nbk, - swn = bn * nbk, - extra_bindings = extra_bindings, - setup = setup, - a_row = a_row, - ) +/// The hole whose `name}` starts `tail`: the offset of its closing brace and its text. +fn hole_at<'a>(tail: &str, holes: &'a [(&str, String)]) -> Option<(usize, &'a str)> { + let close = tail.find('}')?; + let (_, text) = holes.iter().find(|(name, _)| *name == &tail[..close])?; + Some((close, text.as_str())) } /// A kernel source with the shared helper functions in front. diff --git a/crates/igpu/src/shaders/gemm_template.rs b/crates/igpu/src/shaders/gemm_template.rs new file mode 100644 index 00000000..dad32f7a --- /dev/null +++ b/crates/igpu/src/shaders/gemm_template.rs @@ -0,0 +1,94 @@ +//! The WGSL text of the integer matrix product: the fixed part, with `{name}` holes that `gemm` fills. + +/// Holes: `bm bn nbk ta tb sam swn tm tn loads_a loads_b a_row` (numbers), `extra_bindings setup` (plain or grouped +/// product), `weight_word weight_scale` (weight format) and the unrolled `declare_acc declare_sum operands multiply +/// scales scale store`. Braces outside a hole are WGSL. +pub(super) const TEMPLATE: &str = r#" +requires packed_4x8_integer_dot_product; + +struct Dims { m: u32, n: u32, nb: u32, flags: u32 } // flags: 1 adds bias[n], 2 adds the existing output +@group(0) @binding(0) var dims: Dims; +@group(0) @binding(1) var wq: array; +@group(0) @binding(2) var ws: array; +@group(0) @binding(3) var aq: array; +@group(0) @binding(4) var asc: array; +@group(0) @binding(5) var c: array; +@group(0) @binding(6) var bias: array; +{extra_bindings} + +const BM: u32 = {bm}u; +const BN: u32 = {bn}u; +const NBK: u32 = {nbk}u; + +var tile_a: array; // NBK blocks +var tile_b: array; +var sa_tile: array; +var sw_tile: array; + +// the MXFP4 value table (twice the E2M1 value) as magnitudes packed one per nibble: 0 1 2 3 4 6 8 12 +fn mxfp4_magnitude(nibble: u32) -> i32 { + return i32((0xC8643210u >> (4u * (nibble & 7u))) & 15u); +} + +// four nibbles (taken from the low or the high half of each byte of `word`) as four packed int8 values +fn decode_mxfp4(word: u32, high: bool) -> u32 { + var out = 0u; + for (var t = 0u; t < 4u; t++) { + let byte = (word >> (8u * t)) & 255u; + let nibble = select(byte & 15u, byte >> 4u, high); + let magnitude = mxfp4_magnitude(nibble); + let value = select(magnitude, -magnitude, nibble >= 8u); + out |= (u32(value) & 255u) << (8u * t); + } + return out; +} + +@compute @workgroup_size(8, 8) +fn main(@builtin(local_invocation_id) lid: vec3, + @builtin(workgroup_id) wid: vec3) { + let tx = lid.x; + let ty = lid.y; + let flat = ty * 8u + tx; +{setup} + let col0 = wid.x * BN; +{declare_acc} + for (var kb0 = 0u; kb0 < dims.nb; kb0 += NBK) { + for (var sub = 0u; sub < NBK; sub++) { + let kb = kb0 + sub; + let live = kb < dims.nb; + for (var i = 0u; i < {loads_a}u; i++) { + let idx = flat + i * 64u; + let r = idx / 8u; + let w = idx % 8u; + var v = 0u; + if (live && row0 + r < rows_valid) { v = aq[{a_row} * dims.nb * 8u + kb * 8u + w]; } + tile_a[(sub * 8u + w) * BM + (r % {tm}u) * 8u + r / {tm}u] = v; + } + for (var i = 0u; i < {loads_b}u; i++) { + let idx = flat + i * 64u; + let r = idx / 8u; + let w = idx % 8u; + var v = 0u; + if (live && col0 + r < dims.n) { v = {weight_word}; } + tile_b[(sub * 8u + w) * BN + (r % {tn}u) * 8u + r / {tn}u] = v; + } + if (flat < BM) { + var v = 0.0; + if (live && row0 + flat < rows_valid) { let r = flat; v = asc[{a_row} * dims.nb + kb]; } + sa_tile[sub * BM + flat] = v; + } + if (flat < BN) { + let r = flat; + sw_tile[sub * BN + r] = 0.0; + if (live && col0 + r < dims.n) { {weight_scale} } + } + } + workgroupBarrier(); + for (var sub = 0u; sub < NBK; sub++) { +{declare_sum} for (var kk = 0u; kk < 8u; kk++) { +{operands}{multiply} } +{scales}{scale} } + workgroupBarrier(); + } +{store}} +"#; diff --git a/crates/npu-service/src/engine/impl_engine.rs b/crates/npu-service/src/engine/impl_engine.rs index ed834f60..86cb67ef 100644 --- a/crates/npu-service/src/engine/impl_engine.rs +++ b/crates/npu-service/src/engine/impl_engine.rs @@ -80,7 +80,8 @@ impl Engine { let p = &self.profile; let ms = |d: Duration| d.as_secs_f64() * 1e3; format!( - "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not prefetched) {:.0} | run on the device incl. prefetch {:.0}", + "{} products: read activations {:.0} ms | slots/compile {:.0} | expand weights (not \ + prefetched) {:.0} | run on the device incl. prefetch {:.0}", p.calls, ms(p.read_in), ms(p.compile), diff --git a/crates/npu-worker/src/main.rs b/crates/npu-worker/src/main.rs index cddd5806..721a70b4 100644 --- a/crates/npu-worker/src/main.rs +++ b/crates/npu-worker/src/main.rs @@ -35,7 +35,9 @@ struct Args { } fn usage() -> &'static str { - "usage: leleka-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" + "usage: leleka-npu-worker --serve --model --openvino-root [--npu-service \ + ] [--npu-device NPU] [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] \ + [--no-warm] [--seed N] [--speculate] [--cache-slots N]" } /// The options as they are read, before the required ones are checked. diff --git a/crates/openvino/src/c_api_types.rs b/crates/openvino/src/c_api_types.rs index 0edb7dac..104d9b92 100644 --- a/crates/openvino/src/c_api_types.rs +++ b/crates/openvino/src/c_api_types.rs @@ -38,26 +38,57 @@ pub(super) struct RawDevices { pub(super) type Status = i32; +/// The loaded entry points, in the groups of the C header. pub(super) struct Fns { + pub(super) core: CoreFns, + pub(super) devices: DevicesFns, + pub(super) model: ModelFns, + pub(super) compile: CompileFns, + pub(super) request: RequestFns, + pub(super) tensor: TensorFns, +} + +/// The library and core entry points. +pub(super) struct CoreFns { pub(super) err_msg: unsafe extern "C" fn() -> *const c_char, pub(super) core_create: unsafe extern "C" fn(*mut *mut c_void) -> Status, pub(super) core_free: unsafe extern "C" fn(*mut c_void), +} + +/// Device enumeration and properties. +pub(super) struct DevicesFns { pub(super) get_devices: unsafe extern "C" fn(*const c_void, *mut RawDevices) -> Status, pub(super) free_devices: unsafe extern "C" fn(*mut RawDevices), pub(super) get_property: unsafe extern "C" fn(*const c_void, *const c_char, *const c_char, *mut *mut c_char) -> Status, pub(super) free_str: unsafe extern "C" fn(*const c_char), +} + +/// Reading a model. +pub(super) struct ModelFns { pub(super) read_model_mem: unsafe extern "C" fn(*const c_void, *const c_char, usize, *const c_void, *mut *mut c_void) -> Status, pub(super) model_free: unsafe extern "C" fn(*mut c_void), +} + +/// Compiling a model. +pub(super) struct CompileFns { pub(super) compile: unsafe extern "C" fn(*const c_void, *const c_void, *const c_char, usize, *mut *mut c_void, ...) -> Status, pub(super) compiled_free: unsafe extern "C" fn(*mut c_void), +} + +/// Inference requests. +pub(super) struct RequestFns { pub(super) new_request: unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status, pub(super) request_free: unsafe extern "C" fn(*mut c_void), pub(super) set_input: unsafe extern "C" fn(*mut c_void, usize, *const c_void) -> Status, pub(super) get_output: unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> Status, pub(super) infer: unsafe extern "C" fn(*mut c_void) -> Status, +} + +/// Shapes and tensors. +pub(super) struct TensorFns { pub(super) shape_create: unsafe extern "C" fn(i64, *const i64, *mut RawShape) -> Status, pub(super) shape_free: unsafe extern "C" fn(*mut RawShape) -> Status, pub(super) tensor_create: unsafe extern "C" fn(u32, RawShape, *mut *mut c_void) -> Status, diff --git a/crates/openvino/src/compile_and_infer.rs b/crates/openvino/src/compile_and_infer.rs index 9bc45079..f8a32eed 100644 --- a/crates/openvino/src/compile_and_infer.rs +++ b/crates/openvino/src/compile_and_infer.rs @@ -18,7 +18,7 @@ impl Core { pub fn new(ov: &Arc) -> Result { let mut raw = std::ptr::null_mut(); // SAFETY: `raw` is a valid out pointer. - ov.check(unsafe { (ov.fns.core_create)(&mut raw) }, "ov_core_create")?; + ov.check(unsafe { (ov.fns.core.core_create)(&mut raw) }, "ov_core_create")?; Ok(Self { ov: ov.clone(), raw, @@ -42,7 +42,7 @@ impl Core { }; // SAFETY: valid core and out pointer. self.ov.check( - unsafe { (self.ov.fns.get_devices)(self.raw, &mut raw) }, + unsafe { (self.ov.fns.devices.get_devices)(self.raw, &mut raw) }, "ov_core_get_available_devices", )?; let names = (0..raw.size) @@ -54,7 +54,7 @@ impl Core { }) .collect(); // SAFETY: the structure was filled by the call above and is freed once. - unsafe { (self.ov.fns.free_devices)(&mut raw) }; + unsafe { (self.ov.fns.devices.free_devices)(&mut raw) }; Ok(names) } @@ -64,12 +64,12 @@ impl Core { let mut out = std::ptr::null_mut(); // SAFETY: valid core, NUL-terminated strings and out pointer. self.ov.check( - unsafe { (self.ov.fns.get_property)(self.raw, d.as_ptr(), k.as_ptr(), &mut out) }, + unsafe { (self.ov.fns.devices.get_property)(self.raw, d.as_ptr(), k.as_ptr(), &mut out) }, "ov_core_get_property", )?; // SAFETY: on success `out` is a NUL-terminated string allocated by the library, freed once. let value = unsafe { CStr::from_ptr(out) }.to_string_lossy().into_owned(); - unsafe { (self.ov.fns.free_str)(out) }; + unsafe { (self.ov.fns.devices.free_str)(out) }; Ok(value) } @@ -79,12 +79,12 @@ impl Core { let mut model = std::ptr::null_mut(); // SAFETY: valid core, the XML text with its length, a valid tensor and an out pointer. self.ov.check( - unsafe { (self.ov.fns.read_model_mem)(self.raw, xml.as_ptr().cast(), xml.len(), wt.raw, &mut model) }, + unsafe { (self.ov.fns.model.read_model_mem)(self.raw, xml.as_ptr().cast(), xml.len(), wt.raw, &mut model) }, "ov_core_read_model_from_memory_buffer", )?; let compiled = self.compile_model(model, device); // SAFETY: the model was created above and is not needed once compiled (or if compiling failed). - unsafe { (self.ov.fns.model_free)(model) }; + unsafe { (self.ov.fns.model.model_free)(model) }; Ok(Compiled { ov: self.ov.clone(), raw: compiled?, @@ -101,7 +101,7 @@ impl Core { // arguments, not the pairs). let status = unsafe { match &self.cache_dir { - Some(dir) => (self.ov.fns.compile)( + Some(dir) => (self.ov.fns.compile.compile)( self.raw, model, d.as_ptr(), @@ -110,7 +110,7 @@ impl Core { key.as_ptr(), dir.as_ptr(), ), - None => (self.ov.fns.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled), + None => (self.ov.fns.compile.compile)(self.raw, model, d.as_ptr(), 0usize, &mut compiled), } }; self.ov.check(status, "ov_core_compile_model")?; @@ -121,7 +121,7 @@ impl Core { impl Drop for Core { fn drop(&mut self) { // SAFETY: created by ov_core_create, freed once. - unsafe { (self.ov.fns.core_free)(self.raw) }; + unsafe { (self.ov.fns.core.core_free)(self.raw) }; } } @@ -139,7 +139,7 @@ impl Compiled { let mut raw = std::ptr::null_mut(); // SAFETY: valid compiled model and out pointer. self.ov.check( - unsafe { (self.ov.fns.new_request)(self.raw, &mut raw) }, + unsafe { (self.ov.fns.request.new_request)(self.raw, &mut raw) }, "ov_compiled_model_create_infer_request", )?; Ok(Request { @@ -152,7 +152,7 @@ impl Compiled { impl Drop for Compiled { fn drop(&mut self) { // SAFETY: created by ov_core_compile_model, freed once. - unsafe { (self.ov.fns.compiled_free)(self.raw) }; + unsafe { (self.ov.fns.compile.compiled_free)(self.raw) }; } } @@ -171,7 +171,7 @@ impl Request { pub fn set_input(&mut self, index: usize, tensor: &Tensor) -> Result<(), Error> { // SAFETY: valid request and tensor. self.ov.check( - unsafe { (self.ov.fns.set_input)(self.raw, index, tensor.raw) }, + unsafe { (self.ov.fns.request.set_input)(self.raw, index, tensor.raw) }, "ov_infer_request_set_input_tensor_by_index", ) } @@ -179,7 +179,7 @@ impl Request { pub fn infer(&mut self) -> Result<(), Error> { // SAFETY: valid request. self.ov - .check(unsafe { (self.ov.fns.infer)(self.raw) }, "ov_infer_request_infer") + .check(unsafe { (self.ov.fns.request.infer)(self.raw) }, "ov_infer_request_infer") } /// Output number `index` of the last run. The tensor is owned by the caller (a handle to the request's @@ -188,7 +188,7 @@ impl Request { let mut raw = std::ptr::null_mut(); // SAFETY: valid request and out pointer. self.ov.check( - unsafe { (self.ov.fns.get_output)(self.raw, index, &mut raw) }, + unsafe { (self.ov.fns.request.get_output)(self.raw, index, &mut raw) }, "ov_infer_request_get_output_tensor_by_index", )?; Ok(Tensor { @@ -202,6 +202,6 @@ impl Request { impl Drop for Request { fn drop(&mut self) { // SAFETY: created by ov_compiled_model_create_infer_request, freed once. - unsafe { (self.ov.fns.request_free)(self.raw) }; + unsafe { (self.ov.fns.request.request_free)(self.raw) }; } } diff --git a/crates/openvino/src/lib.rs b/crates/openvino/src/lib.rs index 032783e2..5191ebdc 100644 --- a/crates/openvino/src/lib.rs +++ b/crates/openvino/src/lib.rs @@ -29,7 +29,7 @@ mod error; pub use error::Error; mod c_api_types; pub use c_api_types::Element; -use c_api_types::{Fns, RawDevices, RawShape, Status}; +use c_api_types::{CompileFns, CoreFns, DevicesFns, Fns, ModelFns, RawDevices, RawShape, RequestFns, Status, TensorFns}; mod library; pub use library::OpenVino; mod compile_and_infer; diff --git a/crates/openvino/src/library.rs b/crates/openvino/src/library.rs index 10b414cf..262ae43e 100644 --- a/crates/openvino/src/library.rs +++ b/crates/openvino/src/library.rs @@ -15,83 +15,12 @@ impl OpenVino { // SAFETY: loading a library runs its initialisation code; the caller names the file. let lib = unsafe { Library::new(path) }.map_err(|e| Error::Load(format!("{}: {e}", path.display())))?; let fns = Fns { - err_msg: load!(lib, "ov_get_last_err_msg", unsafe extern "C" fn() -> *const c_char), - core_create: load!(lib, "ov_core_create", unsafe extern "C" fn(*mut *mut c_void) -> Status), - core_free: load!(lib, "ov_core_free", unsafe extern "C" fn(*mut c_void)), - get_devices: load!( - lib, - "ov_core_get_available_devices", - unsafe extern "C" fn(*const c_void, *mut RawDevices) -> Status - ), - free_devices: load!(lib, "ov_available_devices_free", unsafe extern "C" fn(*mut RawDevices)), - get_property: load!( - lib, - "ov_core_get_property", - unsafe extern "C" fn(*const c_void, *const c_char, *const c_char, *mut *mut c_char) -> Status - ), - free_str: load!(lib, "ov_free", unsafe extern "C" fn(*const c_char)), - read_model_mem: load!( - lib, - "ov_core_read_model_from_memory_buffer", - unsafe extern "C" fn(*const c_void, *const c_char, usize, *const c_void, *mut *mut c_void) -> Status - ), - model_free: load!(lib, "ov_model_free", unsafe extern "C" fn(*mut c_void)), - compile: load!( - lib, - "ov_core_compile_model", - unsafe extern "C" fn( - *const c_void, - *const c_void, - *const c_char, - usize, - *mut *mut c_void, - ... - ) -> Status - ), - compiled_free: load!(lib, "ov_compiled_model_free", unsafe extern "C" fn(*mut c_void)), - new_request: load!( - lib, - "ov_compiled_model_create_infer_request", - unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status - ), - request_free: load!(lib, "ov_infer_request_free", unsafe extern "C" fn(*mut c_void)), - set_input: load!( - lib, - "ov_infer_request_set_input_tensor_by_index", - unsafe extern "C" fn(*mut c_void, usize, *const c_void) -> Status - ), - get_output: load!( - lib, - "ov_infer_request_get_output_tensor_by_index", - unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> Status - ), - infer: load!( - lib, - "ov_infer_request_infer", - unsafe extern "C" fn(*mut c_void) -> Status - ), - shape_create: load!( - lib, - "ov_shape_create", - unsafe extern "C" fn(i64, *const i64, *mut RawShape) -> Status - ), - shape_free: load!(lib, "ov_shape_free", unsafe extern "C" fn(*mut RawShape) -> Status), - tensor_create: load!( - lib, - "ov_tensor_create", - unsafe extern "C" fn(u32, RawShape, *mut *mut c_void) -> Status - ), - tensor_from_host: load!( - lib, - "ov_tensor_create_from_host_ptr", - unsafe extern "C" fn(u32, RawShape, *mut c_void, *mut *mut c_void) -> Status - ), - tensor_data: load!( - lib, - "ov_tensor_data", - unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status - ), - tensor_free: load!(lib, "ov_tensor_free", unsafe extern "C" fn(*mut c_void)), + core: load_core(&lib)?, + devices: load_devices(&lib)?, + model: load_model(&lib)?, + compile: load_compile(&lib)?, + request: load_request(&lib)?, + tensor: load_tensor(&lib)?, }; Ok(Arc::new(Self { fns, _lib: lib })) } @@ -102,7 +31,7 @@ impl OpenVino { } // SAFETY: the function returns a NUL-terminated string owned by the library, or null. let message = unsafe { - let p = (self.fns.err_msg)(); + let p = (self.fns.core.err_msg)(); if p.is_null() { String::new() } else { @@ -112,3 +41,116 @@ impl OpenVino { Err(Error::Call { what, status, message }) } } + +/// The library and core entry points. +fn load_core(lib: &Library) -> Result { + Ok(CoreFns { + err_msg: load!(lib, "ov_get_last_err_msg", unsafe extern "C" fn() -> *const c_char), + core_create: load!(lib, "ov_core_create", unsafe extern "C" fn(*mut *mut c_void) -> Status), + core_free: load!(lib, "ov_core_free", unsafe extern "C" fn(*mut c_void)), + }) +} + +/// Device enumeration and properties. +fn load_devices(lib: &Library) -> Result { + Ok(DevicesFns { + get_devices: load!( + lib, + "ov_core_get_available_devices", + unsafe extern "C" fn(*const c_void, *mut RawDevices) -> Status + ), + free_devices: load!(lib, "ov_available_devices_free", unsafe extern "C" fn(*mut RawDevices)), + get_property: load!( + lib, + "ov_core_get_property", + unsafe extern "C" fn(*const c_void, *const c_char, *const c_char, *mut *mut c_char) -> Status + ), + free_str: load!(lib, "ov_free", unsafe extern "C" fn(*const c_char)), + }) +} + +/// Reading a model. +fn load_model(lib: &Library) -> Result { + Ok(ModelFns { + read_model_mem: load!( + lib, + "ov_core_read_model_from_memory_buffer", + unsafe extern "C" fn(*const c_void, *const c_char, usize, *const c_void, *mut *mut c_void) -> Status + ), + model_free: load!(lib, "ov_model_free", unsafe extern "C" fn(*mut c_void)), + }) +} + +/// Compiling a model. +fn load_compile(lib: &Library) -> Result { + Ok(CompileFns { + compile: load!( + lib, + "ov_core_compile_model", + unsafe extern "C" fn( + *const c_void, + *const c_void, + *const c_char, + usize, + *mut *mut c_void, + ... + ) -> Status + ), + compiled_free: load!(lib, "ov_compiled_model_free", unsafe extern "C" fn(*mut c_void)), + }) +} + +/// Inference requests. +fn load_request(lib: &Library) -> Result { + Ok(RequestFns { + new_request: load!( + lib, + "ov_compiled_model_create_infer_request", + unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status + ), + request_free: load!(lib, "ov_infer_request_free", unsafe extern "C" fn(*mut c_void)), + set_input: load!( + lib, + "ov_infer_request_set_input_tensor_by_index", + unsafe extern "C" fn(*mut c_void, usize, *const c_void) -> Status + ), + get_output: load!( + lib, + "ov_infer_request_get_output_tensor_by_index", + unsafe extern "C" fn(*const c_void, usize, *mut *mut c_void) -> Status + ), + infer: load!( + lib, + "ov_infer_request_infer", + unsafe extern "C" fn(*mut c_void) -> Status + ), + }) +} + +/// Shapes and tensors. +fn load_tensor(lib: &Library) -> Result { + Ok(TensorFns { + shape_create: load!( + lib, + "ov_shape_create", + unsafe extern "C" fn(i64, *const i64, *mut RawShape) -> Status + ), + shape_free: load!(lib, "ov_shape_free", unsafe extern "C" fn(*mut RawShape) -> Status), + tensor_create: load!( + lib, + "ov_tensor_create", + unsafe extern "C" fn(u32, RawShape, *mut *mut c_void) -> Status + ), + tensor_from_host: load!( + lib, + "ov_tensor_create_from_host_ptr", + unsafe extern "C" fn(u32, RawShape, *mut c_void, *mut *mut c_void) -> Status + ), + tensor_data: load!( + lib, + "ov_tensor_data", + unsafe extern "C" fn(*const c_void, *mut *mut c_void) -> Status + ), + tensor_free: load!(lib, "ov_tensor_free", unsafe extern "C" fn(*mut c_void)), + }) +} diff --git a/crates/openvino/src/tensor.rs b/crates/openvino/src/tensor.rs index e42b97f1..e2ad0e3a 100644 --- a/crates/openvino/src/tensor.rs +++ b/crates/openvino/src/tensor.rs @@ -29,7 +29,7 @@ pub(super) fn with_shape( }; // SAFETY: `dims` is valid for its length and `shape` is a valid out pointer. ov.check( - unsafe { (ov.fns.shape_create)(dims.len() as i64, dims.as_ptr(), &mut shape) }, + unsafe { (ov.fns.tensor.shape_create)(dims.len() as i64, dims.as_ptr(), &mut shape) }, "ov_shape_create", )?; // The tensor constructors copy the dimensions, so the shape can be freed right after the call. @@ -38,7 +38,7 @@ pub(super) fn with_shape( dims: shape.dims, }); // SAFETY: the shape was created above and is freed once. - unsafe { (ov.fns.shape_free)(&mut shape) }; + unsafe { (ov.fns.tensor.shape_free)(&mut shape) }; result } @@ -49,7 +49,7 @@ impl Tensor { // SAFETY: the shape is valid for the call; `raw` is a valid out pointer. with_shape(ov, dims, |shape| { ov.check( - unsafe { (ov.fns.tensor_create)(element as u32, shape, &mut raw) }, + unsafe { (ov.fns.tensor.tensor_create)(element as u32, shape, &mut raw) }, "ov_tensor_create", ) })?; @@ -79,7 +79,7 @@ impl Tensor { // SAFETY: forwarded from the caller's contract. with_shape(ov, dims, |shape| { ov.check( - unsafe { (ov.fns.tensor_from_host)(element as u32, shape, ptr.cast(), &mut raw) }, + unsafe { (ov.fns.tensor.tensor_from_host)(element as u32, shape, ptr.cast(), &mut raw) }, "ov_tensor_create_from_host_ptr", ) })?; @@ -95,7 +95,7 @@ impl Tensor { let mut p = std::ptr::null_mut(); // SAFETY: valid tensor and out pointer. self.ov - .check(unsafe { (self.ov.fns.tensor_data)(self.raw, &mut p) }, "ov_tensor_data")?; + .check(unsafe { (self.ov.fns.tensor.tensor_data)(self.raw, &mut p) }, "ov_tensor_data")?; Ok(p.cast()) } @@ -146,6 +146,6 @@ impl Drop for Tensor { fn drop(&mut self) { // SAFETY: created by one of the tensor constructors or ov_infer_request_get_output_tensor_by_index, // each of which returns a handle that is freed exactly once. - unsafe { (self.ov.fns.tensor_free)(self.raw) }; + unsafe { (self.ov.fns.tensor.tensor_free)(self.raw) }; } } diff --git a/crates/serving-policy/src/watchdog.rs b/crates/serving-policy/src/watchdog.rs index ac249050..87002e7b 100644 --- a/crates/serving-policy/src/watchdog.rs +++ b/crates/serving-policy/src/watchdog.rs @@ -120,7 +120,8 @@ pub fn stage_text(location: &str, detail: i64, chunk: i64) -> String { /// The line the watchdog prints before it stops the engine. pub fn stall_message(limit_s: i64, stage: &str) -> String { format!( - "strata serve: no progress for {limit_s} s during a request ({stage}) - stopping the engine so the server starts it again (issue #29)" + "strata serve: no progress for {limit_s} s during a request ({stage}) - stopping the \ + engine so the server starts it again (issue #29)" ) } diff --git a/limits-allowlist.json b/limits-allowlist.json index 6c3dbeee..45261768 100644 --- a/limits-allowlist.json +++ b/limits-allowlist.json @@ -1475,26 +1475,6 @@ "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", "owner": "STRA-338" }, - { - "path": "crates/gptoss-npu/src/accelerator.rs", - "name": "PrefillAccelerator for NpuPrefill::admit", - "fn_lines": 18, - "complexity": 2, - "nesting": 1, - "width": 1, - "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", - "owner": "STRA-338" - }, - { - "path": "crates/gptoss/src/profile.rs", - "name": "Profile::report", - "fn_lines": 24, - "complexity": 1, - "nesting": 0, - "width": 1, - "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", - "owner": "STRA-338" - }, { "path": "crates/gptoss/src/tests.rs", "name": "the_kar_probe_loses_less_with_more_levels_and_keeps_q8_0_layout", @@ -1532,16 +1512,6 @@ "reason": "moved verbatim by the size split of STRA-338 (size-rest); not yet decomposed", "owner": "STRA-338" }, - { - "path": "crates/openvino/src/library.rs", - "name": "OpenVino::load", - "fn_lines": 84, - "complexity": 2, - "nesting": 1, - "width": 0, - "reason": "FFI symbol table: about 25 dlsym lookups bound to the C API by name; the table is the point, not logic", - "owner": "STRA-338" - }, { "path": "crates/tokenizer/src/decoding.rs", "name": "", diff --git a/limits-baseline.json b/limits-baseline.json index 9f89b6c0..7f647d45 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -34,35 +34,13 @@ "fn_lines": 4 }, "leleka-experimental-ref": { - "width": 4 + "width": 3 }, "leleka-gateway-domain": { "width": 16 }, "leleka-gateway-text": { - "width": 61 - }, - "leleka-gguf": { - "width": 1 - }, - "leleka-gptoss": { - "width": 1 - }, - "leleka-gptoss-igpu": { - "width": 2 - }, - "leleka-gptoss-npu": { - "width": 2 - }, - "leleka-gpu-npu-worker": { - "width": 2 - }, - "leleka-igpu": { - "fn_lines": 1, - "width": 5 - }, - "leleka-igpu-worker": { - "width": 1 + "width": 59 }, "leleka-libc-shim": { "width": 35, @@ -79,13 +57,10 @@ "width": 9 }, "leleka-npu-service": { - "width": 3 - }, - "leleka-npu-worker": { "width": 2 }, - "leleka-openvino": { - "fn_lines": 1 + "leleka-npu-worker": { + "width": 1 }, "leleka-runtime": { "width": 2 @@ -94,7 +69,7 @@ "width": 3 }, "leleka-serving-policy": { - "width": 5 + "width": 4 }, "leleka-tokenizer": { "width": 14