STRA-338 size-fn2: wide lines of cpu-sys, cpu-kernels, cpu-worker, gguf, gptoss*, gpu-npu-worker, igpu*, native-parity-bench, npu-*, serving-policy (prod 33 -> 5, test 29 -> 0: comments re-wrapped, message strings broken at a space with a backslash continuation, same bytes; native-parity-bench main split into run_with_context); the five WGSL lines of igpu gemm stay

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 20:04:57 +01:00
parent 0ea7fa75ae
commit dc28184651
45 changed files with 284 additions and 119 deletions
+2 -1
View File
@@ -232,7 +232,8 @@ fn main() {
let variants = build_variants(sys::avxvnni_available(), n_acts);
println!(
"buffer {} MiB = {rows} rows, {n_acts} activation(s); {repeats} interleaved repeats; ratios are paired against the first variant",
"buffer {} MiB = {rows} rows, {n_acts} activation(s); {repeats} interleaved repeats; ratios are paired against \
the first variant",
weights.len() >> 20
);
for threads in [1usize, 10] {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn abi_version, fn check_i8, fn check_i4, fn dot_i8i8_scalar, fn dot_i4i8_scalar, fn avxvnni_available ....
//! Moved out of the parent module by STRA-338: fn abi_version, fn check_i8, fn check_i4, fn dot_i8i8_scalar, fn
//! dot_i4i8_scalar, fn avxvnni_available ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn quantize_q8_0_scalar, fn quantize_q8_0_avx2, fn dot_q8_0_q8_0_scalar, fn q8_0_q8_0_isums_scalar, fn dot_q8_0_q8_0_avx2, fn q8_0_q8_0_isums_avx2 ....
//! Moved out of the parent module by STRA-338: fn quantize_q8_0_scalar, fn quantize_q8_0_avx2, fn dot_q8_0_q8_0_scalar,
//! fn q8_0_q8_0_isums_scalar, fn dot_q8_0_q8_0_avx2, fn q8_0_q8_0_isums_avx2 ....
#[allow(unused_imports)]
use super::*;
+4 -1
View File
@@ -80,7 +80,10 @@ const SEGMENT: usize = 64;
/// Generates a multi-activation kernel. `$decode` fills `w[i]` and `d[i]` (the weight scale) for
/// block `ib`; `$groups` is the number of accumulators of the one-activation kernel (4 or 2).
macro_rules! multi_kernel {
($name:ident, $features:literal, $block_bytes:expr, $p32:ident, $groups:literal, |$xb:ident, $ib:ident| $decode:expr) => {
(
$name:ident, $features:literal, $block_bytes:expr, $p32:ident, $groups:literal,
|$xb:ident, $ib:ident| $decode:expr
) => {
#[target_feature(enable = $features)]
pub unsafe fn $name(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
let nb = x.len() / $block_bytes;
+2 -1
View File
@@ -1,5 +1,6 @@
//! Differential test: the Rust `std::arch` kernels in `simd` must give bit-identical results to the C
//! kernels they replace, for every instruction-set level this machine runs. Needs the c-reference`n//! feature: cargo test -p leleka-cpu-sys --features c-reference --test rust_vs_c.
//! kernels they replace, for every instruction-set level this machine runs. Needs the c-reference`n//! feature: cargo
//! test -p leleka-cpu-sys --features c-reference --test rust_vs_c.
use leleka_cpu_sys::avx2_available;
use leleka_cpu_sys::c_reference as c;
+2 -1
View File
@@ -1,6 +1,7 @@
//! The register-tiled kernels: every tile shape gives, for each (row, activation) pair, exactly the value
//! of the 1x1 tile at the same level, and all of them stay
//! within the float summation tolerance of the portable reference. (AVX2 and AVX-VNNI differ from each\n//! other only in float rounding: they group the integer products into lanes differently.)
//! within the float summation tolerance of the portable reference. (AVX2 and AVX-VNNI differ from each\n//! other only
//! in float rounding: they group the integer products into lanes differently.)
use leleka_cpu_sys as sys;
use leleka_cpu_sys::simd;
+36 -21
View File
@@ -153,30 +153,45 @@ fn parse_settings(args: &[String]) -> Settings {
}
}
/// The system and developer messages every agent starts with.
fn system_header(st: &Settings) -> String {
format!(
"<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: \
2024-06\nCurrent date: 2026-10-17\n\nReasoning: low\n\n# Valid channels: analysis, commentary, final. \
Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n\nYou are a \
coding agent in a Rust repository.\n{}<|end|>",
filler(7, st.header_chars)
)
}
/// The prompts of one agent, one per turn, each tokenized whole.
fn agent_prompts(tokenizer: &GgufBpe, header: &str, a: usize, st: &Settings) -> Vec<Vec<u32>> {
let mut text = format!(
"{header}<|start|>user<|message|>Task {a}: review module number {} and report what it \
does.<|end|><|start|>assistant",
a * 7 + 3
);
(0..st.turns)
.map(|t| {
if t > 0 {
text.push_str(&format!(
concat!(
"<|channel|>final<|message|>Noted.<|end|>",
"<|start|>user<|message|>{}<|end|><|start|>assistant"
),
filler(100 + (a * 10 + t) as u64, st.tool_chars)
));
}
tokenizer.encode(&text, true)
})
.collect()
}
/// prompts[agent][turn]: each tokenized whole, as the control plane does.
fn build_prompts(tokenizer: &GgufBpe, st: &Settings) -> Vec<Vec<Vec<u32>>> {
let header = format!(
"<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2024-06\nCurrent date: 2026-10-17\n\nReasoning: low\n\n# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n\nYou are a coding agent in a Rust repository.\n{}<|end|>",
filler(7, st.header_chars)
);
let header = system_header(st);
(0..st.agents)
.map(|a| {
let mut text = format!(
"{header}<|start|>user<|message|>Task {a}: review module number {} and report what it does.<|end|><|start|>assistant",
a * 7 + 3
);
(0..st.turns)
.map(|t| {
if t > 0 {
text.push_str(&format!(
"<|channel|>final<|message|>Noted.<|end|><|start|>user<|message|>{}<|end|><|start|>assistant",
filler(100 + (a * 10 + t) as u64, st.tool_chars)
));
}
tokenizer.encode(&text, true)
})
.collect()
})
.map(|a| agent_prompts(tokenizer, &header, a, st))
.collect()
}
+4 -2
View File
@@ -28,11 +28,13 @@ mod policy_replay;
const TASKS: [(&str, &str); 4] = [
(
"rewrite",
"Rewrite the whole file with the function `sample` renamed to `draw_token` and `argmax` renamed to `best_index`. Output only the code.",
"Rewrite the whole file with the function `sample` renamed to `draw_token` and `argmax` renamed to \
`best_index`. Output only the code.",
),
(
"diff",
"Write a unified diff for this file that adds `#[inline]` on the line before every `pub fn`. Output only the diff.",
"Write a unified diff for this file that adds `#[inline]` on the line before every `pub fn`. Output only the \
diff.",
),
(
"json",
+2 -1
View File
@@ -257,7 +257,8 @@ impl Decoder for GptOssEngine {
Ok(done) => return Ok(done.map(|r| r.reused)),
Err(e) => {
eprintln!(
"leleka-cpu-worker: accelerated prefill failed ({e}); redoing it on the CPU and disabling the accelerator"
"leleka-cpu-worker: accelerated prefill failed ({e}); redoing it on the CPU and disabling the \
accelerator"
);
self.accelerator = None;
}
+4 -2
View File
@@ -1,4 +1,5 @@
//! `leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]`
//! `leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]
//! [--cache-slots N]`
//!
//! Started by the control plane, which writes requests to its standard input and reads protocol lines
//! from its standard output (see `protocol`). Logs go to standard error.
@@ -22,7 +23,8 @@ struct Args {
}
fn usage() -> &'static str {
"usage: leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]"
"usage: leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N] \
[--speculate] [--cache-slots N]"
}
/// The options as they are read, before the required ones are checked.
+2 -1
View File
@@ -1,4 +1,5 @@
//! The line protocol the control plane speaks to an inference worker. The grammar lives in `leleka-worker-protocol`, shared with the
//! The line protocol the control plane speaks to an inference worker. The grammar lives in `leleka-worker-protocol`,
//! shared with the
//! gateway that reads these lines; this module keeps the old `leleka_cpu_worker::protocol` paths.
pub use leleka_worker_protocol::command::{Command, Generate, parse_command};
+2 -1
View File
@@ -37,7 +37,8 @@ impl DecodeTimes {
}
}
format!(
"decode {:.0} ms = passes{passes} (tokens:count x mean ms) | sample {:.0} | write {:.0} | draft {:.0} | truncate {:.0} | other {:.0}",
"decode {:.0} ms = passes{passes} (tokens:count x mean ms) | sample {:.0} | write {:.0} | draft {:.0} | \
truncate {:.0} | other {:.0}",
ms(total),
ms(self.sample),
ms(self.write),
+2 -1
View File
@@ -102,7 +102,8 @@ fn print_types_and_ceiling(inv: &Inventory, bandwidth: f64) {
println!(" {:<8} {:>10.1} MB", t.name(), *b as f64 / 1e6);
}
println!(
"\nstreaming every per-token byte at {bandwidth:.1} GB/s gives a decode ceiling of {:.1} tokens/s (a bound, not a prediction)",
"\nstreaming every per-token byte at {bandwidth:.1} GB/s gives a decode ceiling of {:.1} tokens/s (a bound, \
not a prediction)",
inv.ceiling_tokens_per_second(bandwidth)
);
for note in &inv.notes {
+2 -1
View File
@@ -294,7 +294,8 @@ 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
+2 -1
View File
@@ -3,7 +3,8 @@
//! the page cache and the machine state are shared. Warm only: each path is run once untimed first. Prints
//! every run, the distribution per path and the paired speed-up with a 95% confidence interval.
//!
//! Run: `cargo run --release -p leleka-gptoss-igpu --example ab_prefill -- <model.gguf> <tokens[,tokens...]> <pairs> [batch]`
//! Run: `cargo run --release -p leleka-gptoss-igpu --example ab_prefill -- <model.gguf> <tokens[,tokens...]> <pairs>
//! [batch]`
//! Set `LELEKA_MODEL_SHA256` to record the model digest in the report.
use leleka_cpu_kernels::Dispatch;
@@ -2,7 +2,8 @@
//! `dump_logprobs` of the CPU decoder, so `compare_logprobs` can compare it with llama.cpp's reference.
//! Every position's hidden state comes from the GPU prefill; the output projection runs on the CPU.
//!
//! Run: `cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- <model.gguf> <ids.txt> <out.jsonl> [top_n] [batch]`
//! Run: `cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- <model.gguf> <ids.txt> <out.jsonl>
//! [top_n] [batch]`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
+2 -1
View File
@@ -3,7 +3,8 @@
//! decoded by the CPU from each cache. Also reports the times. Correctness probe, not a benchmark: one
//! run, the machine state is not controlled.
//!
//! Run: `cargo run --release -p leleka-gptoss-igpu --example gpu_prefill -- <model.gguf> <ids|synth:N> [decode_tokens] [batch]`
//! Run: `cargo run --release -p leleka-gptoss-igpu --example gpu_prefill -- <model.gguf> <ids|synth:N> [decode_tokens]
//! [batch]`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
+4 -2
View File
@@ -226,7 +226,8 @@ 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 +279,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
);
+2 -1
View File
@@ -3,7 +3,8 @@
//! the page cache and the machine state are shared. Warm only: each path is run once untimed first. Prints
//! every run, the distribution per path and the paired speed-up with a 95% confidence interval.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example ab_prefill_npu -- <model.gguf> <openvino root> <service exe> <device> <tokens[,tokens...]> <pairs> [batch]`
//! Run: `cargo run --release -p leleka-gptoss-npu --example ab_prefill_npu -- <model.gguf> <openvino root> <service
//! exe> <device> <tokens[,tokens...]> <pairs> [batch]`
//! Set `LELEKA_MODEL_SHA256` to record the model digest in the report.
use leleka_cpu_kernels::Dispatch;
@@ -2,7 +2,8 @@
//! as `dump_logprobs` of the CPU decoder, so `compare_logprobs` can compare it with llama.cpp's reference.
//! Every position's hidden state comes from the NPU prefill; the output projection runs on the CPU.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example dump_logprobs_npu -- <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]`
//! Run: `cargo run --release -p leleka-gptoss-npu --example dump_logprobs_npu -- <model.gguf> <openvino root> <service
//! exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
@@ -80,7 +81,8 @@ fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() < 6 {
eprintln!(
"usage: dump_logprobs_npu <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [batch]"
"usage: dump_logprobs_npu <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> \
[top_n] [batch]"
);
std::process::exit(2);
}
+2 -1
View File
@@ -1,7 +1,8 @@
//! Prefill the same prompt on the CPU and with the NPU service and compare what they leave behind (last-token
//! distribution, KV caches, greedy continuation) and the times.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example npu_prefill -- <model.gguf> <openvino root> <service exe> <device> <ids|synth:N> [batch] [decode]`
//! Run: `cargo run --release -p leleka-gptoss-npu --example npu_prefill -- <model.gguf> <openvino root> <service exe>
//! <device> <ids|synth:N> [batch] [decode]`
//! Set `LELEKA_SKIP_CPU=1` to time the NPU path only.
use leleka_cpu_kernels::Dispatch;
+2 -1
View File
@@ -2,7 +2,8 @@
//! hidden states of a few tokens, multiplies them by the layer-0 value projection (Q8_0) in f64 as the reference
//! and through the NPU service on the given devices, and prints the relative rms errors.
//!
//! Run: `cargo run --release -p leleka-gptoss-npu --example numerics_probe -- <model.gguf> <openvino root> <service exe> <device,device...>`
//! Run: `cargo run --release -p leleka-gptoss-npu --example numerics_probe -- <model.gguf> <openvino root> <service
//! exe> <device,device...>`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
+2 -1
View File
@@ -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
);
+3 -1
View File
@@ -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),
+4 -2
View File
@@ -2,9 +2,11 @@
//! `forward` for one token, `logits_after_each` for a batch. The cache is cut back to the prompt after every pass,
//! sizes are interleaved in a different order each round, and the median per size is printed.
//! With `ab` every pass runs twice back to back, without and with the multi-activation kernels
//! ([`Model::set_multi_activation`], identical values), alternating which goes first, and the paired ratios are printed.
//! ([`Model::set_multi_activation`], identical values), alternating which goes first, and the paired ratios are
//! printed.
//!
//! Run: `cargo run --release -p leleka-gptoss --example batch_cost -- <model.gguf> [prompt_tokens] [max_n] [rounds] [threads] [ab]`
//! Run: `cargo run --release -p leleka-gptoss --example batch_cost -- <model.gguf> [prompt_tokens] [max_n] [rounds]
//! [threads] [ab]`
//! The prompt is deterministic pseudo-random ids. Machine state is not controlled.
use leleka_cpu_kernels::Dispatch;
+2 -1
View File
@@ -1,6 +1,7 @@
//! Compare two teacher-forced log-probability dumps (see `dump_logprobs`): ours and a reference.
//!
//! Run: `cargo run --release -p leleka-gptoss --example compare_logprobs -- <ours.jsonl> <reference.jsonl> [skip_first]`
//! Run: `cargo run --release -p leleka-gptoss --example compare_logprobs -- <ours.jsonl> <reference.jsonl>
//! [skip_first]`
//! Reports, over the positions that both files describe: how often the best token agrees, the
//! log-probability differences of tokens present in both top lists, a KL divergence restricted to the
//! shared top tokens, and the mean negative log-likelihood of the actual next token under each side
+2 -1
View File
@@ -2,7 +2,8 @@
//! top-N log-probabilities of the next token (one JSON object per line), for comparison with another
//! implementation fed the same tokens.
//!
//! Run: `cargo run --release -p leleka-gptoss --example dump_logprobs -- <model.gguf> <ids.txt> <out.jsonl> [threads] [top_n]`
//! Run: `cargo run --release -p leleka-gptoss --example dump_logprobs -- <model.gguf> <ids.txt> <out.jsonl> [threads]
//! [top_n]`
//! `ids.txt` holds comma-separated token ids. Line `i` of the output describes the distribution after
//! token `i` (so it predicts token `i + 1`): `{"pos":i,"next":<id of token i+1 or null>,"top":[[id,logprob],...]}`.
+4 -2
View File
@@ -1,6 +1,7 @@
//! Run the decoder on a real gpt-oss GGUF from token ids and print the greedy continuation.
//!
//! Run: `cargo run --release -p leleka-gptoss --example run_real -- <model.gguf> <ids,comma,separated> [new_tokens] [threads]`
//! Run: `cargo run --release -p leleka-gptoss --example run_real -- <model.gguf> <ids,comma,separated> [new_tokens]
//! [threads]`
//! Output: one line `ids: [...]` with the generated token ids, the top-5 log-probabilities of the first
//! generated position, and the per-token timings. Correctness probe, not a benchmark: it is single
//! stream, the first tokens page the weights in, and the machine state is not controlled.
@@ -171,7 +172,8 @@ fn print_summary(
let mean = decode_ms.iter().sum::<f64>() / decode_ms.len().max(1) as f64;
println!("{}", state.profile.report());
println!(
"prefill {} tokens in {:.0} ms; decode mean {:.0} ms per token ({:.2} tokens/s) over {} tokens (cold start, uncontrolled machine)",
"prefill {} tokens in {:.0} ms; decode mean {:.0} ms per token ({:.2} tokens/s) over {} tokens (cold start, \
uncontrolled machine)",
prompt_len,
prefill_ms,
mean,
+2 -1
View File
@@ -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),
@@ -1,4 +1,5 @@
//! The decoder against the f64 reference, every instruction-set level, the sliding window, overflow, and chunked prefill.
//! The decoder against the f64 reference, every instruction-set level, the sliding window, overflow, and chunked
//! prefill.
#[allow(unused_imports)]
use super::*;
@@ -2,7 +2,8 @@
//! the tokens through the NPU service, the rest on the GPU): the format of `dump_logprobs`, for `compare_logprobs`.
//! Every position's hidden state comes from the split prefill; the output projection runs on the CPU.
//!
//! Run: `cargo run --release -p leleka-gpu-npu-worker --example dump_logprobs_split -- <model.gguf> <openvino root> <service exe> <device> <ids.txt> <out.jsonl> [top_n] [npu share]`
//! Run: `cargo run --release -p leleka-gpu-npu-worker --example dump_logprobs_split -- <model.gguf> <openvino root>
//! <service exe> <device> <ids.txt> <out.jsonl> [top_n] [npu share]`
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
+2 -1
View File
@@ -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
);
+3 -1
View File
@@ -43,7 +43,9 @@ struct Args {
}
fn usage() -> &'static str {
"usage: leleka-gpu-npu-worker --serve --model <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--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 <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] \
[--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.
+2 -1
View File
@@ -30,7 +30,8 @@ struct Args {
}
fn usage() -> &'static str {
"usage: leleka-igpu-worker --serve --model <gpt-oss.gguf> [--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 <gpt-oss.gguf> [--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.
+141 -47
View File
@@ -1,49 +1,143 @@
//! Actual CUDA acquisition for the unchanged Original benchmark frontend (moved out of leleka-native-cpu-expert so that the CPU
//! expert adapter does not depend on the CUDA driver; STRA-338 S11).
//! Actual CUDA acquisition for the unchanged Original benchmark frontend (moved out of
//! leleka-native-cpu-expert so that the CPU expert adapter does not depend on the CUDA driver;
//! STRA-338 S11).
#![allow(unsafe_code)]
#[cfg(all(target_os="linux",target_pointer_width="64"))]
use leleka_native_cpu_expert::{rust_bench_frontend::{self,gpu::ParityGpu},rust_ggml::NativeFormat};
#[cfg(all(target_os="linux",target_pointer_width="64"))]
mod platform{
use super::*;
use leleka_cuda_driver::{Context,Driver,NativeParity,NativeParityExpert};
pub struct NativeGpu<'ctx>{owner:NativeParity<'ctx>}
impl<'ctx> NativeGpu<'ctx>{pub fn new(context:&'ctx Context<'ctx>)->Result<Self,String>{Ok(Self{owner:context.native_parity()?})}}
impl<'ctx> ParityGpu for NativeGpu<'ctx>{
type Expert=NativeParityExpert<'ctx>;
fn prepare_expert(&mut self,f:&NativeFormat,blob:&[u8],input:&[f32])->Result<Self::Expert,String>{f.validate().map_err(|e|format!("{e:?}"))?;if f.n_embd!=2560||f.n_ff!=640{return Err("Original benchmark geometry".into());}self.owner.prepare_expert(f.gu.original_id(),f.down.original_id(),blob,input)}
fn enqueue_expert(&mut self,e:&mut Self::Expert)->Result<(),String>{self.owner.enqueue_expert(e)}
fn download_expert(&mut self,e:&mut Self::Expert)->Result<Vec<f32>,String>{self.owner.download_expert(e)}
fn old_kernels(&self)->bool{self.owner.old_kernels()}
fn set_old_kernels(&mut self,old:bool){self.owner.set_old_kernels(old)}
fn dequantize_expert_role(&mut self,e:&Self::Expert,role:usize)->Result<(Vec<f32>,Vec<u16>),String>{self.owner.dequantize_expert_role(e,role)}
fn embed_expert_gate(&mut self,e:&Self::Expert,rows:&[i32])->Result<Vec<f32>,String>{self.owner.embed_expert_gate(e,rows)}
fn release_expert(&mut self,e:Self::Expert)->Result<(),String>{self.owner.release_expert(e)}
fn q5_one_min(&mut self,w:&[u8],x:&[f32])->Result<(Vec<f32>,Vec<u8>),String>{self.owner.q5_one_min(w,x)}
fn embed_type_supported(&self,t:i32)->bool{leleka_cuda_driver::native_parity_embed_supported(t)}
fn iq_supported(&self,t:i32)->bool{leleka_cuda_driver::native_parity_iq_supported(t)}
fn row_bytes(&self,t:i32,n:usize)->usize{leleka_cuda_driver::native_parity_row_bytes(t,n)}
fn bf16_embedding(&mut self,t:&[u16],ids:&[i32])->Result<(Vec<f32>,Vec<f32>),String>{self.owner.bf16_embedding(t,ids)}
fn close(self)->Result<(),String>{self.owner.close()}
}
pub fn main()->i32{
let args:Vec<String>=std::env::args().collect();
if args.len()<2{return rust_bench_frontend::unbound_main();}
// This is the process-entry leaf, before CUDA/native pool can start threads.
// SAFETY: set_var is sound only while no other thread touches the environment: this is the first action of the process-entry
// leaf (src/bin/native_expert_parity.rs `fn main`), before Driver::load/create_context (CUDA starts threads) or any native pool
// thread exists. `pub fn main` must therefore never be called from a multithreaded host.
if std::env::var_os("STRATA_IQ_MT_MIN").is_none(){unsafe{std::env::set_var("STRATA_IQ_MT_MIN","1");}}
let acquired:Result<i32,String>=(||{let driver=Driver::load().map_err(|e|e.to_string())?;let device=driver.device(0).map_err(|e|e.to_string())?;let context=device.create_context(isize::MAX as usize).map_err(|e|e.to_string())?;
// All expert owners die inside run; actual Context is closed afterwards.
// SAFETY: `run`'s contract asks for process entry before any thread; the CUDA context above violates that, which is benign only
// because STRATA_IQ_MT_MIN was set above, so run()'s absent-only setenv branch is never taken.
let code=unsafe{rust_bench_frontend::run(&args,||NativeGpu::new(&context))};
let close=context.close().map_err(|e|e.to_string());if code!=0{return Ok(code);}close?;Ok(0)
})();match acquired{Ok(code)=>code,Err(e)=>{eprintln!("{e}");1}}
}
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
use leleka_native_cpu_expert::{
rust_bench_frontend::{self, gpu::ParityGpu},
rust_ggml::NativeFormat,
};
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
mod platform {
use super::*;
use leleka_cuda_driver::{Context, Driver, NativeParity, NativeParityExpert};
pub struct NativeGpu<'ctx> {
owner: NativeParity<'ctx>,
}
impl<'ctx> NativeGpu<'ctx> {
pub fn new(context: &'ctx Context<'ctx>) -> Result<Self, String> {
Ok(Self {
owner: context.native_parity()?,
})
}
}
impl<'ctx> ParityGpu for NativeGpu<'ctx> {
type Expert = NativeParityExpert<'ctx>;
fn prepare_expert(
&mut self,
f: &NativeFormat,
blob: &[u8],
input: &[f32],
) -> Result<Self::Expert, String> {
f.validate().map_err(|e| format!("{e:?}"))?;
if f.n_embd != 2560 || f.n_ff != 640 {
return Err("Original benchmark geometry".into());
}
self.owner
.prepare_expert(f.gu.original_id(), f.down.original_id(), blob, input)
}
fn enqueue_expert(&mut self, e: &mut Self::Expert) -> Result<(), String> {
self.owner.enqueue_expert(e)
}
fn download_expert(&mut self, e: &mut Self::Expert) -> Result<Vec<f32>, String> {
self.owner.download_expert(e)
}
fn old_kernels(&self) -> bool {
self.owner.old_kernels()
}
fn set_old_kernels(&mut self, old: bool) {
self.owner.set_old_kernels(old)
}
fn dequantize_expert_role(
&mut self,
e: &Self::Expert,
role: usize,
) -> Result<(Vec<f32>, Vec<u16>), String> {
self.owner.dequantize_expert_role(e, role)
}
fn embed_expert_gate(
&mut self,
e: &Self::Expert,
rows: &[i32],
) -> Result<Vec<f32>, String> {
self.owner.embed_expert_gate(e, rows)
}
fn release_expert(&mut self, e: Self::Expert) -> Result<(), String> {
self.owner.release_expert(e)
}
fn q5_one_min(&mut self, w: &[u8], x: &[f32]) -> Result<(Vec<f32>, Vec<u8>), String> {
self.owner.q5_one_min(w, x)
}
fn embed_type_supported(&self, t: i32) -> bool {
leleka_cuda_driver::native_parity_embed_supported(t)
}
fn iq_supported(&self, t: i32) -> bool {
leleka_cuda_driver::native_parity_iq_supported(t)
}
fn row_bytes(&self, t: i32, n: usize) -> usize {
leleka_cuda_driver::native_parity_row_bytes(t, n)
}
fn bf16_embedding(
&mut self,
t: &[u16],
ids: &[i32],
) -> Result<(Vec<f32>, Vec<f32>), String> {
self.owner.bf16_embedding(t, ids)
}
fn close(self) -> Result<(), String> {
self.owner.close()
}
}
pub fn main() -> i32 {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
return rust_bench_frontend::unbound_main();
}
// This is the process-entry leaf, before CUDA/native pool can start threads.
// SAFETY: set_var is sound only while no other thread touches the environment: this is the first
// action of the process-entry leaf (src/bin/native_expert_parity.rs `fn main`), before
// Driver::load/create_context (CUDA starts threads) or any native pool thread exists.
// `pub fn main` must therefore never be called from a multithreaded host.
if std::env::var_os("STRATA_IQ_MT_MIN").is_none() {
unsafe {
std::env::set_var("STRATA_IQ_MT_MIN", "1");
}
}
match run_with_context(&args) {
Ok(code) => code,
Err(e) => {
eprintln!("{e}");
1
}
}
}
/// Acquire the CUDA context, run the frontend inside it and close the context afterwards.
fn run_with_context(args: &[String]) -> Result<i32, String> {
let driver = Driver::load().map_err(|e| e.to_string())?;
let device = driver.device(0).map_err(|e| e.to_string())?;
let context = device
.create_context(isize::MAX as usize)
.map_err(|e| e.to_string())?;
// All expert owners die inside run; actual Context is closed afterwards.
// SAFETY: `run`'s contract asks for process entry before any thread; the CUDA context above
// violates that, which is benign only because STRATA_IQ_MT_MIN was set above, so run()'s
// absent-only setenv branch is never taken.
let code = unsafe { rust_bench_frontend::run(args, || NativeGpu::new(&context)) };
let close = context.close().map_err(|e| e.to_string());
if code != 0 {
return Ok(code);
}
close?;
Ok(0)
}
}
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
pub fn main() -> i32 {
platform::main()
}
#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
pub fn main() -> i32 {
eprintln!("Original CUDA parity requires Linux with 64-bit pointers");
1
}
#[cfg(all(target_os="linux",target_pointer_width="64"))]
pub fn main()->i32{platform::main()}
#[cfg(not(all(target_os="linux",target_pointer_width="64")))]
pub fn main()->i32{eprintln!("Original CUDA parity requires Linux with 64-bit pointers");1}
+2 -1
View File
@@ -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),
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Weights, fn ov_error, impl Runtime, fn two_mut, fn load, fn io_error ....
//! Moved out of the parent module by STRA-338: impl Weights, fn ov_error, impl Runtime, fn two_mut, fn load, fn
//! io_error ....
#[allow(unused_imports)]
use super::*;
+2 -1
View File
@@ -2,7 +2,8 @@
//!
//! Client to service: `PING`, `MM <tensor> <expert|-> <rows> <in_offset> <out_offset>`, `BATCH <n>` followed by
//! `n` `MM` lines, `QUIT`.
//! Service to client: `READY <device name>` once at start, then `PONG`, `OK <micros> <bucket> <shifted>` or `ERR <message>`
//! Service to client: `READY <device name>` once at start, then `PONG`, `OK <micros> <bucket> <shifted>` or `ERR
//! <message>`
//! per line. Offsets are byte offsets into the shared region; activations and results are half floats.
use crate::engine::{Done, Product};
+2 -1
View File
@@ -243,7 +243,8 @@ fn compare(env: &Env, svc: &mut Service, name: &str, expert: Option<usize>, rows
}
let (rel, worst, shown) = product_errors((&x, &w, &out, &shifts), (rows, n, k));
eprintln!(
"{name} expert {expert:?} rows {rows}: relative rms error {rel:.2e}, worst abs {worst:.3e}, shifted columns {}, {answer}\n error by eighth of the columns: {}",
"{name} expert {expert:?} rows {rows}: relative rms error {rel:.2e}, worst abs {worst:.3e}, shifted columns \
{}, {answer}\n error by eighth of the columns: {}",
shifts.iter().filter(|s| **s > 0).count(),
shown.join(" ")
);
+5 -2
View File
@@ -1,5 +1,6 @@
//! `leleka-npu-worker --serve --model <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--npu-device NPU]
//! [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]` (experimental)
//! [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]`
//! (experimental)
//!
//! The CPU worker's decoder and protocol with one addition: prompts that need at least `--npu-min-tokens`
//! tokens computed have their matrix products run by the NPU service process (`leleka-npu-service`, which
@@ -35,7 +36,9 @@ struct Args {
}
fn usage() -> &'static str {
"usage: leleka-npu-worker --serve --model <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--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 <gpt-oss.gguf> --openvino-root <dir> [--npu-service <exe>] [--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.
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn build_tables, fn parse_scaled_list, fn strtof_exact, fn parse_dir, fn parse_mode.
//! Moved out of the parent module by STRA-338: fn build_tables, fn parse_scaled_list, fn strtof_exact, fn parse_dir, fn
//! parse_mode.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Cursor, fn value, fn parse_gguf, impl Default_for_Options, fn strtol.
//! Moved out of the parent module by STRA-338: impl Cursor, fn value, fn parse_gguf, impl Default_for_Options, fn
//! strtol.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl SharedDefaults, fn float_value, fn py_repr, fn py_str_repr, fn is_number, fn as_f64 ....
//! Moved out of the parent module by STRA-338: impl SharedDefaults, fn float_value, fn py_repr, fn py_str_repr, fn
//! is_number, fn as_f64 ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn sampling_defaults_from_config, fn normalize_aliases, fn merged_defaults, impl MergedDefaults, fn shared_max_tokens.
//! Moved out of the parent module by STRA-338: fn sampling_defaults_from_config, fn normalize_aliases, fn
//! merged_defaults, impl MergedDefaults, fn shared_max_tokens.
#[allow(unused_imports)]
use super::*;
+4 -2
View File
@@ -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)"
)
}
@@ -225,7 +226,8 @@ mod tests {
);
assert_eq!(
stall_message(60, "layer 12"),
"strata serve: no progress for 60 s during a request (layer 12) - stopping the engine so the server starts it again (issue #29)"
"strata serve: no progress for 60 s during a request (layer 12) - stopping the engine so the server starts \
it again (issue #29)"
);
}
}