experiment: real KAR codec quality on gpt-oss-20b and concurrent iGPU+NPU prefill (STRA-220)
The KAR codec moves unchanged from control-plane/src/kar_codec.rs into crates/kar-codec (re-exported there, so the control plane's KAR tests are unchanged and pass). Probes, off unless set: LELEKA_EXPERIMENTAL_KAR_LEVELS / _KAR_TENSORS for attention and output weights, and LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS / _KAR_EXPERT_LAYERS for the MXFP4 experts (level 0 is a storage-only control). Teacher-forced against llama.cpp, baseline KL 0.016: attention+output at 6.5/5.5/4.5 bits give KL 0.063/0.095/0.213 (uniform rounding was 0.071/0.112/0.270), and every tensor group fails alone; experts of 6 of 24 layers at 3.5 bits give KL 0.081 (control 0.018). No KAR rate passes the gate on this model. Corrects the earlier doc claim that a KAR layout is the same as uniform rounding. iGPU and NPU prefill run at the same time give 93-98 tok/s in total against 73-77 for the faster device alone (2048 tokens each, two rounds). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f3bc0ab695
commit
f3c4e122d8
Generated
+6
@@ -1287,6 +1287,7 @@ dependencies = [
|
||||
"leleka-cpu-kernels",
|
||||
"leleka-cpu-sys",
|
||||
"leleka-gguf",
|
||||
"leleka-kar-codec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1340,6 +1341,10 @@ dependencies = [
|
||||
"sysinfo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-kar-codec"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "leleka-npu-service"
|
||||
version = "0.1.0"
|
||||
@@ -2558,6 +2563,7 @@ dependencies = [
|
||||
"jsonschema",
|
||||
"leleka-gguf",
|
||||
"leleka-harmony",
|
||||
"leleka-kar-codec",
|
||||
"leleka-tokenizer",
|
||||
"libc",
|
||||
"regex",
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
|
||||
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/tokenizer", "control-plane", "desktop-core"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# iGPU and NPU prefill alone and at the same time (separate processes), 2026-10-16
|
||||
model: gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB); synthetic ids, 2048 tokens
|
||||
gpu: examples/gpu_prefill (Vulkan, batch 512, LELEKA_SKIP_CPU=1); npu: examples/npu_prefill (leleka-npu-service, Intel AI Boost, batch 2048, graphs cached, LELEKA_SKIP_CPU=1)
|
||||
base commit c581730 (branch kar-quality-probe); machine otherwise idle (no other leleka/benchmark process; browser, OneDrive, EDR running); power and clocks not controlled
|
||||
per-device times are the prefill alone (model mapping, device setup and service start excluded); the two prefill windows overlap but do not start at the same instant
|
||||
|
||||
r1-gpu wall 31.2 s | gpu: gpu prefill: 2048 tokens in 28.16 s (72.7 tok/s), next 27 | npu:
|
||||
r1-npu wall 32.7 s | gpu: | npu: npu prefill: 2048 tokens in 29.32 s (69.8 tok/s), next 27
|
||||
r1-both wall 43.9 s | gpu: gpu prefill: 2048 tokens in 34.49 s (59.4 tok/s), next 27 | npu: npu prefill: 2048 tokens in 41.56 s (49.3 tok/s), next 27
|
||||
r2-gpu wall 29.5 s | gpu: gpu prefill: 2048 tokens in 26.76 s (76.5 tok/s), next 27 | npu:
|
||||
r2-npu wall 29.5 s | gpu: | npu: npu prefill: 2048 tokens in 27.46 s (74.6 tok/s), next 27
|
||||
r2-both wall 46.2 s | gpu: gpu prefill: 2048 tokens in 34.69 s (59.0 tok/s), next 27 | npu: npu prefill: 2048 tokens in 43.86 s (46.7 tok/s), next 27
|
||||
|
||||
aggregate when both run: 4096 tokens / longest prefill = 98.5 tok/s (r1), 93.4 tok/s (r2); best device alone 72.7-76.5 tok/s
|
||||
|
||||
uncontrolled observation (not a result): gpu_prefill of 2048 tokens while a CPU worker benchmark decoded on 14 threads ran at 37.4-39.2 tok/s instead of 70.9
|
||||
@@ -0,0 +1,120 @@
|
||||
# real KAR codec roundtrip, teacher-forced against llama.cpp (benchmarks/quality/gpt-oss-20b-teacher-forced/set2/table-igpu, 770 positions)
|
||||
model: gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB); dump_logprobs 14 threads, top 20; avx-vnni
|
||||
codec: crates/kar-codec (moved unchanged from control-plane/src/kar_codec.rs), group 32, codebook fitted per tensor to 65,536 evenly sampled values; reconstruction stored as Q8_0
|
||||
baseline (8-bit attention/output, MXFP4 experts): 93.4% agreement, mean KL 0.016 (docs/cpu-runtime.md)
|
||||
date: 2026-10-16; the first table was built in the shared checkout and reproduced exactly (4 levels, all tensors) from a clean worktree build
|
||||
|
||||
## attention + output weights, LELEKA_EXPERIMENTAL_KAR_LEVELS=3..6
|
||||
levels 3 done in 185 s
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 307/770 positions (39.9%)
|
||||
|difference| of the best token's log-probability: mean 0.7083, max 2.8101
|
||||
|difference| over all shared top-20 tokens: mean 1.0740, max 19.1056 (8699 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.55743, max 6.31522
|
||||
mean NLL of the actual next token over 270 positions: ours 3.0557, reference 2.2564 (difference +0.7993); 499 positions had it outside a top list
|
||||
by position (count, mean |d top|, mean KL, best-token agreement):
|
||||
0..9 n=10 0.3497 0.24180 60%
|
||||
10..29 n=20 0.5145 0.61057 70%
|
||||
30..59 n=30 0.6246 0.95645 37%
|
||||
60..99 n=40 0.5629 0.65195 45%
|
||||
100..199 n=100 0.6679 0.49850 47%
|
||||
200..end n=570 0.7431 0.54381 37%
|
||||
largest best-token differences: pos 265: 2.810, pos 105: 2.777, pos 697: 2.683, pos 391: 2.594, pos 710: 2.570
|
||||
levels 4 done in 163 s
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 524/770 positions (68.1%)
|
||||
|difference| of the best token's log-probability: mean 0.3816, max 2.4864
|
||||
|difference| over all shared top-20 tokens: mean 0.5913, max 9.2826 (11683 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.21328, max 6.62943
|
||||
mean NLL of the actual next token over 350 positions: ours 2.7265, reference 2.5046 (difference +0.2219); 419 positions had it outside a top list
|
||||
by position (count, mean |d top|, mean KL, best-token agreement):
|
||||
0..9 n=10 0.1013 0.03300 90%
|
||||
10..29 n=20 0.2352 0.32692 70%
|
||||
30..59 n=30 0.3898 0.46370 67%
|
||||
60..99 n=40 0.3101 0.43152 72%
|
||||
100..199 n=100 0.3576 0.17255 68%
|
||||
200..end n=570 0.4005 0.19110 67%
|
||||
largest best-token differences: pos 472: 2.486, pos 714: 2.191, pos 268: 1.970, pos 29: 1.909, pos 452: 1.856
|
||||
levels 5 done in 158 s
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 611/770 positions (79.4%)
|
||||
|difference| of the best token's log-probability: mean 0.2210, max 1.9191
|
||||
|difference| over all shared top-20 tokens: mean 0.3564, max 6.2864 (13137 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.09482, max 1.74321
|
||||
mean NLL of the actual next token over 366 positions: ours 2.6508, reference 2.5619 (difference +0.0889); 403 positions had it outside a top list
|
||||
by position (count, mean |d top|, mean KL, best-token agreement):
|
||||
0..9 n=10 0.1203 0.06200 80%
|
||||
10..29 n=20 0.2318 0.14368 85%
|
||||
30..59 n=30 0.2708 0.15547 80%
|
||||
60..99 n=40 0.1839 0.10824 90%
|
||||
100..199 n=100 0.1701 0.06149 78%
|
||||
200..end n=570 0.2313 0.09539 79%
|
||||
largest best-token differences: pos 261: 1.919, pos 447: 1.700, pos 238: 1.421, pos 714: 1.397, pos 640: 1.300
|
||||
levels 6 done in 150 s
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 646/770 positions (83.9%)
|
||||
|difference| of the best token's log-probability: mean 0.1584, max 1.3144
|
||||
|difference| over all shared top-20 tokens: mean 0.2546, max 5.9330 (13857 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.06255, max 2.80275
|
||||
mean NLL of the actual next token over 378 positions: ours 2.6658, reference 2.6358 (difference +0.0300); 391 positions had it outside a top list
|
||||
by position (count, mean |d top|, mean KL, best-token agreement):
|
||||
0..9 n=10 0.0517 0.00537 90%
|
||||
10..29 n=20 0.1820 0.11677 80%
|
||||
30..59 n=30 0.2317 0.15084 70%
|
||||
60..99 n=40 0.1209 0.05713 90%
|
||||
100..199 n=100 0.1345 0.04953 85%
|
||||
200..end n=570 0.1625 0.05966 84%
|
||||
largest best-token differences: pos 487: 1.314, pos 238: 1.294, pos 382: 1.274, pos 714: 1.161, pos 572: 1.125
|
||||
|
||||
## one group at a time, 4 levels (LELEKA_EXPERIMENTAL_KAR_TENSORS)
|
||||
== levels 4, tensors output.weight
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 615/770 positions (79.9%)
|
||||
|difference| of the best token's log-probability: mean 0.2021, max 1.6173
|
||||
|difference| over all shared top-20 tokens: mean 0.2983, max 4.5421 (13487 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.06187, max 1.40561
|
||||
mean NLL of the actual next token over 372 positions: ours 2.6550, reference 2.6007 (difference +0.0544); 397 positions had it outside a top list
|
||||
== levels 4, tensors attn_q,attn_k
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 582/770 positions (75.6%)
|
||||
|difference| of the best token's log-probability: mean 0.2342, max 1.9492
|
||||
|difference| over all shared top-20 tokens: mean 0.4088, max 9.1422 (12864 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.12049, max 4.32719
|
||||
mean NLL of the actual next token over 368 positions: ours 2.7062, reference 2.5863 (difference +0.1199); 401 positions had it outside a top list
|
||||
== levels 4, tensors attn_v,attn_output
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 559/770 positions (72.6%)
|
||||
|difference| of the best token's log-probability: mean 0.3176, max 2.0886
|
||||
|difference| over all shared top-20 tokens: mean 0.4883, max 10.3942 (12182 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.17176, max 9.18236
|
||||
mean NLL of the actual next token over 357 positions: ours 2.6826, reference 2.5441 (difference +0.1385); 412 positions had it outside a top list
|
||||
== levels 4, tensors attn_,output.weight
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 524/770 positions (68.1%)
|
||||
|difference| of the best token's log-probability: mean 0.3816, max 2.4864
|
||||
|difference| over all shared top-20 tokens: mean 0.5913, max 9.2826 (11683 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.21328, max 6.62943
|
||||
mean NLL of the actual next token over 350 positions: ours 2.7265, reference 2.5046 (difference +0.2219); 419 positions had it outside a top list
|
||||
|
||||
## experts of layers 0-5 (LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS, _LAYERS=0-5); 4 levels could not be fitted (too few distinct values)
|
||||
== expert levels 3, layers 0-5
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 661/770 positions (85.8%)
|
||||
|difference| of the best token's log-probability: mean 0.1573, max 1.7111
|
||||
|difference| over all shared top-20 tokens: mean 0.2635, max 13.6500 (13710 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.08140, max 11.80278
|
||||
mean NLL of the actual next token over 374 positions: ours 2.6124, reference 2.6097 (difference +0.0027); 395 positions had it outside a top list
|
||||
== expert levels 2, layers 0-5
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 561/770 positions (72.9%)
|
||||
|difference| of the best token's log-probability: mean 0.3446, max 2.3022
|
||||
|difference| over all shared top-20 tokens: mean 0.4884, max 8.4988 (12480 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.16637, max 6.23427
|
||||
mean NLL of the actual next token over 375 positions: ours 2.5340, reference 2.6268 (difference -0.0928); 394 positions had it outside a top list
|
||||
== expert levels 0 (control: Q8_0 storage without KAR), layers 0-5
|
||||
positions: ours 770, reference 770, compared 770
|
||||
best token agrees at 712/770 positions (92.5%)
|
||||
|difference| of the best token's log-probability: mean 0.0796, max 1.0772
|
||||
|difference| over all shared top-20 tokens: mean 0.1281, max 4.0103 (14534 values)
|
||||
KL(reference || ours) on shared top tokens: mean 0.01823, max 0.99799
|
||||
mean NLL of the actual next token over 378 positions: ours 2.6274, reference 2.6345 (difference -0.0071); 391 positions had it outside a top list
|
||||
@@ -14,6 +14,7 @@ axum = "0.8"
|
||||
futures-core = "0.3"
|
||||
hex = "0.4"
|
||||
leleka-gguf = { path = "../crates/gguf" }
|
||||
leleka-kar-codec = { path = "../crates/kar-codec" }
|
||||
leleka-harmony = { path = "../crates/harmony" }
|
||||
leleka-tokenizer = { path = "../crates/tokenizer" }
|
||||
http-body = "1"
|
||||
|
||||
@@ -1,343 +1,6 @@
|
||||
//! Experimental KAR scalar calibration, bit-plane encoding, and CPU decoding.
|
||||
//! The caller selects samples and lossy rates; serving does not enable this path.
|
||||
//! Re-export of the shared KAR codec (`crates/kar-codec`), kept under this path for the control plane's callers.
|
||||
|
||||
pub struct EncodedPlanes {
|
||||
pub scales: Vec<u16>,
|
||||
/// Plane zero is the most significant index bit. Bit m of word w belongs
|
||||
/// to weight 32*w+m, matching the koference CUDA decoder.
|
||||
pub planes: Vec<Vec<u32>>,
|
||||
pub padded_elements: usize,
|
||||
}
|
||||
|
||||
pub struct NormalizedTensor {
|
||||
pub scales: Vec<u16>,
|
||||
pub values: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Normalize one finite f32 tensor using the exact rounded f16 group scales
|
||||
/// that the KAR decoder will later multiply back in.
|
||||
pub fn normalize_for_calibration(weights: &[f32], group: u16) -> Result<NormalizedTensor, String> {
|
||||
let group = usize::from(group);
|
||||
if weights.is_empty()
|
||||
|| group == 0
|
||||
|| group > 1024
|
||||
|| !group.is_multiple_of(32)
|
||||
|| weights.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR normalization input".into());
|
||||
}
|
||||
let padded = weights
|
||||
.len()
|
||||
.div_ceil(group)
|
||||
.checked_mul(group)
|
||||
.ok_or("KAR encoder padded size overflow")?;
|
||||
let mut scales = Vec::with_capacity(padded / group);
|
||||
let mut values = Vec::with_capacity(padded);
|
||||
let mut normalized = vec![0.0f32; group];
|
||||
for group_index in 0..padded / group {
|
||||
let start = group_index * group;
|
||||
let end = (start + group).min(weights.len());
|
||||
let scale_bits = normalize_group_into(&weights[start..end], &mut normalized)?;
|
||||
scales.push(scale_bits);
|
||||
values.extend_from_slice(&normalized);
|
||||
}
|
||||
Ok(NormalizedTensor { scales, values })
|
||||
}
|
||||
|
||||
/// Normalize one nonempty group into reusable, padded storage.
|
||||
pub fn normalize_group_into(weights: &[f32], output: &mut [f32]) -> Result<u16, String> {
|
||||
if weights.is_empty()
|
||||
|| weights.len() > output.len()
|
||||
|| output.is_empty()
|
||||
|| output.len() > 1024
|
||||
|| !output.len().is_multiple_of(32)
|
||||
|| weights.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR normalization input".into());
|
||||
}
|
||||
let maximum = weights
|
||||
.iter()
|
||||
.map(|value| value.abs())
|
||||
.fold(0.0f32, f32::max);
|
||||
if maximum > 65504.0 || (maximum != 0.0 && maximum < f32::from_bits(0x3380_0000)) {
|
||||
return Err("KAR scale overflows or underflows f16".into());
|
||||
}
|
||||
let scale = if maximum == 0.0 {
|
||||
f32::from_bits(0x3380_0000)
|
||||
} else {
|
||||
maximum
|
||||
};
|
||||
let scale_bits = f32_to_f16_bits(scale);
|
||||
let rounded_scale = f16_bits_to_f32(scale_bits);
|
||||
if !rounded_scale.is_finite() || rounded_scale == 0.0 {
|
||||
return Err("KAR rounded scale is invalid".into());
|
||||
}
|
||||
for (position, value) in output.iter_mut().enumerate() {
|
||||
*value = weights
|
||||
.get(position)
|
||||
.map_or(0.0, |weight| *weight / rounded_scale);
|
||||
}
|
||||
Ok(scale_bits)
|
||||
}
|
||||
|
||||
pub struct Calibration {
|
||||
pub boundaries: Vec<f32>,
|
||||
/// One f16 reconstruction table per level, from level 1 upward.
|
||||
pub books: Vec<Vec<u16>>,
|
||||
}
|
||||
|
||||
/// Fit koference's top-down nested scalar partitions to an already selected,
|
||||
/// normalized sample. Sampling policy and rate selection remain external.
|
||||
pub fn fit_topdown(sample: &[f32], levels: u8) -> Result<Calibration, String> {
|
||||
if !(1..=16).contains(&levels)
|
||||
|| sample.len() < (1usize << levels)
|
||||
|| sample.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR calibration sample or level count".into());
|
||||
}
|
||||
let mut sorted = sample
|
||||
.iter()
|
||||
.map(|value| f64::from(*value))
|
||||
.collect::<Vec<_>>();
|
||||
sorted.sort_unstable_by(f64::total_cmp);
|
||||
let mut sums = Vec::with_capacity(sorted.len() + 1);
|
||||
let mut squares = Vec::with_capacity(sorted.len() + 1);
|
||||
sums.push(0.0);
|
||||
squares.push(0.0);
|
||||
for value in &sorted {
|
||||
sums.push(sums.last().copied().unwrap() + value);
|
||||
squares.push(squares.last().copied().unwrap() + value * value);
|
||||
}
|
||||
let mut cells = vec![(0usize, sorted.len())];
|
||||
let mut boundaries = Vec::with_capacity((1usize << levels) - 1);
|
||||
for _ in 0..levels {
|
||||
let mut next = Vec::with_capacity(cells.len() * 2);
|
||||
for (lo, hi) in cells {
|
||||
let mut best = None;
|
||||
for middle in lo + 1..hi {
|
||||
if sorted[middle - 1] == sorted[middle] {
|
||||
continue;
|
||||
}
|
||||
let left_count = (middle - lo) as f64;
|
||||
let right_count = (hi - middle) as f64;
|
||||
let left_sum = sums[middle] - sums[lo];
|
||||
let right_sum = sums[hi] - sums[middle];
|
||||
let left_cost = squares[middle] - squares[lo] - left_sum * left_sum / left_count;
|
||||
let right_cost =
|
||||
squares[hi] - squares[middle] - right_sum * right_sum / right_count;
|
||||
let cost = left_cost + right_cost;
|
||||
if best.is_none_or(|(_, previous)| cost < previous) {
|
||||
best = Some((middle, cost));
|
||||
}
|
||||
}
|
||||
let (middle, _) = best.ok_or("KAR calibration sample cannot split every cell")?;
|
||||
boundaries.push(((sorted[middle - 1] + sorted[middle]) / 2.0) as f32);
|
||||
next.push((lo, middle));
|
||||
next.push((middle, hi));
|
||||
}
|
||||
cells = next;
|
||||
}
|
||||
boundaries.sort_unstable_by(f32::total_cmp);
|
||||
if boundaries.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return Err("KAR calibration boundaries collapse in f32".into());
|
||||
}
|
||||
let finest = 1usize << levels;
|
||||
let mut counts = vec![0usize; finest];
|
||||
let mut totals = vec![0f64; finest];
|
||||
for value in &sorted {
|
||||
let index = boundaries.partition_point(|boundary| f64::from(*boundary) < *value);
|
||||
counts[index] += 1;
|
||||
totals[index] += value;
|
||||
}
|
||||
let mut books = vec![Vec::new(); usize::from(levels)];
|
||||
for level in (1..=usize::from(levels)).rev() {
|
||||
books[level - 1] = counts
|
||||
.iter()
|
||||
.zip(&totals)
|
||||
.map(|(count, total)| {
|
||||
f64_to_f16_bits(if *count == 0 {
|
||||
0.0
|
||||
} else {
|
||||
*total / *count as f64
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if level > 1 {
|
||||
counts = counts
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| pair[0] + pair[1])
|
||||
.collect();
|
||||
totals = totals
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| pair[0] + pair[1])
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
Ok(Calibration { boundaries, books })
|
||||
}
|
||||
|
||||
/// Decode a bounded range from a selected KAR prefix. `book` is the f16 table
|
||||
/// for exactly `planes.len()` levels; `start` is a flat element index.
|
||||
pub fn decode_range(
|
||||
scales: &[u16],
|
||||
book: &[u16],
|
||||
planes: &[&[u32]],
|
||||
group: u16,
|
||||
start: usize,
|
||||
output: &mut [f32],
|
||||
) -> Result<(), String> {
|
||||
let group = usize::from(group);
|
||||
if group == 0
|
||||
|| group > 1024
|
||||
|| !group.is_multiple_of(32)
|
||||
|| !(1..=16).contains(&planes.len())
|
||||
|| book.len() != 1usize << planes.len()
|
||||
{
|
||||
return Err("invalid KAR decoder geometry or book".into());
|
||||
}
|
||||
let padded = scales
|
||||
.len()
|
||||
.checked_mul(group)
|
||||
.ok_or("KAR decoder padded size overflow")?;
|
||||
let end = start
|
||||
.checked_add(output.len())
|
||||
.ok_or("KAR decoder range overflow")?;
|
||||
if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) {
|
||||
return Err("KAR decoder range or plane length is invalid".into());
|
||||
}
|
||||
if scales[start / group..end.div_ceil(group)]
|
||||
.iter()
|
||||
.any(|bits| bits & 0x7c00 == 0x7c00)
|
||||
|| book.iter().any(|bits| bits & 0x7c00 == 0x7c00)
|
||||
{
|
||||
return Err("KAR decoder received non-finite f16 data".into());
|
||||
}
|
||||
for (relative, value) in output.iter_mut().enumerate() {
|
||||
let position = start + relative;
|
||||
let mut index = 0usize;
|
||||
for plane in planes {
|
||||
let bit = (plane[position / 32] >> (position % 32)) & 1;
|
||||
index = (index << 1) | bit as usize;
|
||||
}
|
||||
*value = f16_bits_to_f32(book[index]) * f16_bits_to_f32(scales[position / group]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn encode_with_boundaries(
|
||||
weights: &[f32],
|
||||
group: u16,
|
||||
boundaries: &[f32],
|
||||
levels: u8,
|
||||
) -> Result<EncodedPlanes, String> {
|
||||
if !(1..=16).contains(&levels) || boundaries.len() != (1usize << levels) - 1 {
|
||||
return Err("invalid KAR encoder shape or calibration".into());
|
||||
}
|
||||
if boundaries.iter().any(|value| !value.is_finite())
|
||||
|| boundaries.windows(2).any(|pair| pair[0] >= pair[1])
|
||||
{
|
||||
return Err("KAR encoder needs increasing finite boundaries".into());
|
||||
}
|
||||
let normalized = normalize_for_calibration(weights, group)?;
|
||||
let padded = normalized.values.len();
|
||||
let words = padded / 32;
|
||||
let mut planes = vec![vec![0u32; words]; usize::from(levels)];
|
||||
for (position, value) in normalized.values.iter().enumerate() {
|
||||
// NumPy searchsorted defaults to side='left': equality stays in
|
||||
// the lower cell, as in koference's reference encoder.
|
||||
let index = boundaries.partition_point(|boundary| *boundary < *value);
|
||||
for (level, plane) in planes.iter_mut().enumerate() {
|
||||
let bit = (index >> (usize::from(levels) - 1 - level)) & 1;
|
||||
plane[position / 32] |= (bit as u32) << (position % 32);
|
||||
}
|
||||
}
|
||||
Ok(EncodedPlanes {
|
||||
scales: normalized.scales,
|
||||
planes,
|
||||
padded_elements: padded,
|
||||
})
|
||||
}
|
||||
|
||||
// IEEE-754 round-to-nearest, ties-to-even conversion, independent of host
|
||||
// f16 support so the Linux control binary and offline oracle agree.
|
||||
pub fn f32_to_f16_bits(value: f32) -> u16 {
|
||||
let bits = value.to_bits();
|
||||
let sign = ((bits >> 16) & 0x8000) as u16;
|
||||
let exponent = ((bits >> 23) & 0xff) as i32;
|
||||
let mantissa = bits & 0x7f_ffff;
|
||||
if exponent == 255 {
|
||||
return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 };
|
||||
}
|
||||
let half_exponent = exponent - 127 + 15;
|
||||
if half_exponent >= 31 {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if half_exponent <= 0 {
|
||||
if half_exponent < -10 {
|
||||
return sign;
|
||||
}
|
||||
let significand = mantissa | 0x80_0000;
|
||||
let shift = (14 - half_exponent) as u32;
|
||||
let rounded =
|
||||
(significand + ((1u32 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift;
|
||||
return sign | rounded as u16;
|
||||
}
|
||||
let rounded = mantissa + 0x0fff + ((mantissa >> 13) & 1);
|
||||
if rounded & 0x80_0000 != 0 {
|
||||
return sign | (((half_exponent + 1) as u16) << 10);
|
||||
}
|
||||
sign | ((half_exponent as u16) << 10) | ((rounded >> 13) as u16)
|
||||
}
|
||||
|
||||
fn f64_to_f16_bits(value: f64) -> u16 {
|
||||
let bits = value.to_bits();
|
||||
let sign = ((bits >> 48) & 0x8000) as u16;
|
||||
let exponent = ((bits >> 52) & 0x7ff) as i32;
|
||||
let mantissa = bits & 0x000f_ffff_ffff_ffff;
|
||||
if exponent == 2047 {
|
||||
return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 };
|
||||
}
|
||||
let half_exponent = exponent - 1023 + 15;
|
||||
if half_exponent >= 31 {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if half_exponent <= 0 {
|
||||
if half_exponent < -10 {
|
||||
return sign;
|
||||
}
|
||||
let significand = mantissa | 0x0010_0000_0000_0000;
|
||||
let shift = (43 - half_exponent) as u32;
|
||||
let rounded =
|
||||
(significand + ((1u64 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift;
|
||||
return sign | rounded as u16;
|
||||
}
|
||||
let rounded = mantissa + 0x0000_01ff_ffff_ffff + ((mantissa >> 42) & 1);
|
||||
if rounded & 0x0010_0000_0000_0000 != 0 {
|
||||
return sign | (((half_exponent + 1) as u16) << 10);
|
||||
}
|
||||
sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16)
|
||||
}
|
||||
|
||||
pub fn f16_bits_to_f32(bits: u16) -> f32 {
|
||||
let sign = (u32::from(bits & 0x8000)) << 16;
|
||||
let exponent = (bits >> 10) & 0x1f;
|
||||
let mantissa = u32::from(bits & 0x03ff);
|
||||
let result = match exponent {
|
||||
0 if mantissa == 0 => sign,
|
||||
0 => {
|
||||
let leading = mantissa.leading_zeros() - 21;
|
||||
let normalized = mantissa << leading;
|
||||
sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13)
|
||||
}
|
||||
31 => sign | 0x7f80_0000 | (mantissa << 13),
|
||||
_ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13),
|
||||
};
|
||||
f32::from_bits(result)
|
||||
}
|
||||
pub use leleka_kar_codec::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -10,6 +10,7 @@ rust-version.workspace = true
|
||||
leleka-cpu-kernels = { path = "../cpu-kernels" }
|
||||
leleka-cpu-sys = { path = "../cpu-sys" }
|
||||
leleka-gguf = { path = "../gguf" }
|
||||
leleka-kar-codec = { path = "../kar-codec" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Tests build tiny quantized models with ggml's own reference quantizers and map files.
|
||||
|
||||
@@ -411,6 +411,138 @@ fn fake_quantize_q8_0(bytes: &[u8], bits: u32) -> Vec<u8> {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// EXPERIMENTAL, quality probe only: `LELEKA_EXPERIMENTAL_KAR_LEVELS=N` (1..=8) passes the attention and output Q8_0
|
||||
/// weights through the real KAR codec (`leleka-kar-codec`: f16 absmax scale per group of 32, then an N-level nested
|
||||
/// codebook fitted to each tensor) and stores the reconstruction in Q8_0, to measure what an N + 0.5 bits per weight
|
||||
/// KAR format would cost in quality. Storing in Q8_0 adds at most half an 8-bit step per block. Gives no speed-up.
|
||||
fn kar_levels_for(name: &str) -> Option<u8> {
|
||||
// `LELEKA_EXPERIMENTAL_KAR_TENSORS=a,b`: only the tensors whose name contains one of these (default: all of them)
|
||||
let selected = std::env::var("LELEKA_EXPERIMENTAL_KAR_TENSORS").map_or(true, |list| {
|
||||
list.split(',')
|
||||
.any(|part| !part.is_empty() && name.contains(part))
|
||||
});
|
||||
if !(name.contains("attn_") || name == "output.weight") || !selected {
|
||||
return None;
|
||||
}
|
||||
std::env::var("LELEKA_EXPERIMENTAL_KAR_LEVELS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u8>().ok())
|
||||
.filter(|l| (1..=8).contains(l))
|
||||
}
|
||||
|
||||
/// Groups of 32 sampled evenly across a tensor to fit its codebook (65,536 values, as the KAR preparer uses).
|
||||
const KAR_SAMPLE_GROUPS: usize = 2048;
|
||||
|
||||
fn kar_roundtrip_q8_0(bytes: &[u8], levels: u8, name: &str) -> Result<Vec<u8>, ModelError> {
|
||||
kar_roundtrip(bytes.as_chunks::<Q8_0_BYTES>().0, levels, name, |block| {
|
||||
let d = half_to_f32(u16::from_le_bytes([block[0], block[1]]));
|
||||
std::array::from_fn(|i| d * f32::from(block[2 + i] as i8))
|
||||
})
|
||||
}
|
||||
|
||||
/// EXPERIMENTAL, quality probe only: `LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS=N` passes the MXFP4 expert weights of
|
||||
/// the layers in `LELEKA_EXPERIMENTAL_KAR_EXPERT_LAYERS=a-b` (inclusive; default all, which needs about 21 GB) through
|
||||
/// the KAR codec as above and stores them in Q8_0 (twice the bytes of MXFP4; the products then take the Q8_0 path).
|
||||
/// `N = 0` is the control: the same Q8_0 storage without KAR.
|
||||
fn kar_expert_levels_for(name: &str) -> Option<u8> {
|
||||
let layer: usize = name.strip_prefix("blk.")?.split('.').next()?.parse().ok()?;
|
||||
if !name.contains("_exps.weight") {
|
||||
return None;
|
||||
}
|
||||
let (first, last) = std::env::var("LELEKA_EXPERIMENTAL_KAR_EXPERT_LAYERS")
|
||||
.ok()
|
||||
.and_then(|r| {
|
||||
let (a, b) = r.split_once('-')?;
|
||||
Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
|
||||
})
|
||||
.unwrap_or((0, usize::MAX));
|
||||
if !(first..=last).contains(&layer) {
|
||||
return None;
|
||||
}
|
||||
std::env::var("LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u8>().ok())
|
||||
.filter(|l| (0..=8).contains(l))
|
||||
}
|
||||
|
||||
fn kar_roundtrip_mxfp4(bytes: &[u8], levels: u8, name: &str) -> Result<Vec<u8>, ModelError> {
|
||||
use leleka_cpu_sys::simd::{KVALUES_MXFP4, e8m0_half};
|
||||
kar_roundtrip(bytes.as_chunks::<MXFP4_BYTES>().0, levels, name, |block| {
|
||||
let d = e8m0_half(block[0]);
|
||||
std::array::from_fn(|i| {
|
||||
// ggml order: low nibbles are elements 0..16, high nibbles 16..32
|
||||
let byte = block[1 + i % 16];
|
||||
let nibble = if i < 16 { byte & 0xF } else { byte >> 4 };
|
||||
d * f32::from(KVALUES_MXFP4[usize::from(nibble)])
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode and decode `blocks` (32 values each, from `dequantize`) with a `levels`-level KAR codebook fitted to an
|
||||
/// even sample of them, and store the reconstruction as Q8_0 blocks.
|
||||
fn kar_roundtrip<const N: usize>(
|
||||
blocks: &[[u8; N]],
|
||||
levels: u8,
|
||||
name: &str,
|
||||
dequantize: impl Fn(&[u8; N]) -> [f32; BLOCK],
|
||||
) -> Result<Vec<u8>, ModelError> {
|
||||
use leleka_kar_codec as kar;
|
||||
let invalid = |e: String| ModelError::Invalid(format!("{name}: KAR probe: {e}"));
|
||||
let mut out = Vec::with_capacity(blocks.len() * Q8_0_BYTES);
|
||||
if levels == 0 {
|
||||
// control: the same Q8_0 storage without KAR
|
||||
for block in blocks {
|
||||
push_q8_0(&dequantize(block), &mut out);
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let step = (blocks.len() / KAR_SAMPLE_GROUPS).max(1);
|
||||
let mut sample = Vec::with_capacity(KAR_SAMPLE_GROUPS * BLOCK);
|
||||
let mut normalized = [0.0f32; BLOCK];
|
||||
for block in blocks.iter().step_by(step) {
|
||||
kar::normalize_group_into(&dequantize(block), &mut normalized).map_err(invalid)?;
|
||||
sample.extend_from_slice(&normalized);
|
||||
}
|
||||
let calibration = kar::fit_topdown(&sample, levels).map_err(invalid)?;
|
||||
let book = &calibration.books[usize::from(levels) - 1];
|
||||
// encode and decode in bounded chunks: groups are independent
|
||||
for chunk in blocks.chunks(1 << 15) {
|
||||
let values: Vec<f32> = chunk.iter().flat_map(&dequantize).collect();
|
||||
let encoded =
|
||||
kar::encode_with_boundaries(&values, BLOCK as u16, &calibration.boundaries, levels)
|
||||
.map_err(invalid)?;
|
||||
let planes: Vec<&[u32]> = encoded.planes.iter().map(Vec::as_slice).collect();
|
||||
let mut decoded = vec![0.0f32; values.len()];
|
||||
kar::decode_range(
|
||||
&encoded.scales,
|
||||
book,
|
||||
&planes,
|
||||
BLOCK as u16,
|
||||
0,
|
||||
&mut decoded,
|
||||
)
|
||||
.map_err(invalid)?;
|
||||
for group in decoded.as_chunks::<BLOCK>().0 {
|
||||
push_q8_0(group, &mut out);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn push_q8_0(group: &[f32; BLOCK], out: &mut Vec<u8>) {
|
||||
let max = group.iter().fold(0.0f32, |m, v| m.max(v.abs()));
|
||||
let d_bits = f32_to_half_bits(max / 127.0);
|
||||
let d = half_to_f32(d_bits);
|
||||
out.extend_from_slice(&d_bits.to_le_bytes());
|
||||
out.extend(group.iter().map(|v| {
|
||||
if d > 0.0 {
|
||||
(v / d).round().clamp(-127.0, 127.0) as i8 as u8
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
fn q_tensor(
|
||||
file: &Arc<dyn ModelBytes>,
|
||||
g: &Gguf,
|
||||
@@ -438,6 +570,34 @@ fn q_tensor(
|
||||
)));
|
||||
}
|
||||
let (offset, len) = bytes_of(file.as_ref(), g, t, name)?;
|
||||
if let (Kind::Mxfp4, Some(levels)) = (kind, kar_expert_levels_for(name)) {
|
||||
let owned = kar_roundtrip_mxfp4(&file.bytes()[offset..offset + len], levels, name)?;
|
||||
eprintln!(
|
||||
"leleka-gptoss: EXPERIMENTAL KAR probe: {name} through {levels}-level KAR, stored as Q8_0"
|
||||
);
|
||||
let len = owned.len();
|
||||
return Ok(QMatrix {
|
||||
bytes: Arc::new(owned),
|
||||
offset: 0,
|
||||
len,
|
||||
rows,
|
||||
cols,
|
||||
kind: Kind::Q8_0,
|
||||
});
|
||||
}
|
||||
if let (Kind::Q8_0, Some(levels)) = (kind, kar_levels_for(name)) {
|
||||
let owned = kar_roundtrip_q8_0(&file.bytes()[offset..offset + len], levels, name)?;
|
||||
eprintln!("leleka-gptoss: EXPERIMENTAL KAR probe: {name} through {levels}-level KAR");
|
||||
let len = owned.len();
|
||||
return Ok(QMatrix {
|
||||
bytes: Arc::new(owned),
|
||||
offset: 0,
|
||||
len,
|
||||
rows,
|
||||
cols,
|
||||
kind,
|
||||
});
|
||||
}
|
||||
if let (Kind::Q8_0, Some(bits)) = (kind, fake_bits_for(name)) {
|
||||
let owned = fake_quantize_q8_0(&file.bytes()[offset..offset + len], bits);
|
||||
let len = owned.len();
|
||||
@@ -1499,6 +1659,50 @@ impl Model {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_kar_probe_loses_less_with_more_levels_and_keeps_q8_0_layout() {
|
||||
// pseudo-random Q8_0 blocks with varied scales
|
||||
let mut s = 0x2545_F491_4F6C_DD1Du64;
|
||||
let mut next = || {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 7;
|
||||
s ^= s << 17;
|
||||
s
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
for b in 0..4096u32 {
|
||||
bytes.extend_from_slice(&f32_to_half_bits(0.001 * (1 + b % 7) as f32).to_le_bytes());
|
||||
bytes.extend((0..BLOCK).map(|_| ((next() % 255) as i32 - 127) as i8 as u8));
|
||||
}
|
||||
let values = |bytes: &[u8]| -> Vec<f32> {
|
||||
bytes
|
||||
.as_chunks::<Q8_0_BYTES>()
|
||||
.0
|
||||
.iter()
|
||||
.flat_map(|blk| {
|
||||
let d = half_to_f32(u16::from_le_bytes([blk[0], blk[1]]));
|
||||
blk[2..].iter().map(move |q| d * f32::from(*q as i8))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let original = values(&bytes);
|
||||
let error = |levels| {
|
||||
let out = kar_roundtrip_q8_0(&bytes, levels, "t").unwrap();
|
||||
assert_eq!(out.len(), bytes.len());
|
||||
let got = values(&out);
|
||||
let num: f64 = original
|
||||
.iter()
|
||||
.zip(&got)
|
||||
.map(|(a, b)| f64::from(a - b).powi(2))
|
||||
.sum();
|
||||
let den: f64 = original.iter().map(|a| f64::from(*a).powi(2)).sum();
|
||||
(num / den).sqrt()
|
||||
};
|
||||
let (e2, e4, e8) = (error(2), error(4), error(8));
|
||||
assert!(e2 > e4 && e4 > e8, "{e2} {e4} {e8}");
|
||||
assert!(e8 < 0.02, "{e8}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_conversion_covers_normal_subnormal_and_special_values() {
|
||||
assert_eq!(half_to_f32(0x3C00), 1.0);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "leleka-kar-codec"
|
||||
version = "0.1.0"
|
||||
description = "KAR scalar calibration, bit-plane encoding and CPU decoding (koference KAR-2 nested codebooks); no dependencies"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,341 @@
|
||||
//! KAR scalar calibration, bit-plane encoding, and CPU decoding (moved from `control-plane/src/kar_codec.rs`,
|
||||
//! whose archive tests still cover it). Experimental: the caller selects samples and lossy rates; serving does not
|
||||
//! enable this path.
|
||||
|
||||
pub struct EncodedPlanes {
|
||||
pub scales: Vec<u16>,
|
||||
/// Plane zero is the most significant index bit. Bit m of word w belongs
|
||||
/// to weight 32*w+m, matching the koference CUDA decoder.
|
||||
pub planes: Vec<Vec<u32>>,
|
||||
pub padded_elements: usize,
|
||||
}
|
||||
|
||||
pub struct NormalizedTensor {
|
||||
pub scales: Vec<u16>,
|
||||
pub values: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Normalize one finite f32 tensor using the exact rounded f16 group scales
|
||||
/// that the KAR decoder will later multiply back in.
|
||||
pub fn normalize_for_calibration(weights: &[f32], group: u16) -> Result<NormalizedTensor, String> {
|
||||
let group = usize::from(group);
|
||||
if weights.is_empty()
|
||||
|| group == 0
|
||||
|| group > 1024
|
||||
|| !group.is_multiple_of(32)
|
||||
|| weights.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR normalization input".into());
|
||||
}
|
||||
let padded = weights
|
||||
.len()
|
||||
.div_ceil(group)
|
||||
.checked_mul(group)
|
||||
.ok_or("KAR encoder padded size overflow")?;
|
||||
let mut scales = Vec::with_capacity(padded / group);
|
||||
let mut values = Vec::with_capacity(padded);
|
||||
let mut normalized = vec![0.0f32; group];
|
||||
for group_index in 0..padded / group {
|
||||
let start = group_index * group;
|
||||
let end = (start + group).min(weights.len());
|
||||
let scale_bits = normalize_group_into(&weights[start..end], &mut normalized)?;
|
||||
scales.push(scale_bits);
|
||||
values.extend_from_slice(&normalized);
|
||||
}
|
||||
Ok(NormalizedTensor { scales, values })
|
||||
}
|
||||
|
||||
/// Normalize one nonempty group into reusable, padded storage.
|
||||
pub fn normalize_group_into(weights: &[f32], output: &mut [f32]) -> Result<u16, String> {
|
||||
if weights.is_empty()
|
||||
|| weights.len() > output.len()
|
||||
|| output.is_empty()
|
||||
|| output.len() > 1024
|
||||
|| !output.len().is_multiple_of(32)
|
||||
|| weights.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR normalization input".into());
|
||||
}
|
||||
let maximum = weights
|
||||
.iter()
|
||||
.map(|value| value.abs())
|
||||
.fold(0.0f32, f32::max);
|
||||
if maximum > 65504.0 || (maximum != 0.0 && maximum < f32::from_bits(0x3380_0000)) {
|
||||
return Err("KAR scale overflows or underflows f16".into());
|
||||
}
|
||||
let scale = if maximum == 0.0 {
|
||||
f32::from_bits(0x3380_0000)
|
||||
} else {
|
||||
maximum
|
||||
};
|
||||
let scale_bits = f32_to_f16_bits(scale);
|
||||
let rounded_scale = f16_bits_to_f32(scale_bits);
|
||||
if !rounded_scale.is_finite() || rounded_scale == 0.0 {
|
||||
return Err("KAR rounded scale is invalid".into());
|
||||
}
|
||||
for (position, value) in output.iter_mut().enumerate() {
|
||||
*value = weights
|
||||
.get(position)
|
||||
.map_or(0.0, |weight| *weight / rounded_scale);
|
||||
}
|
||||
Ok(scale_bits)
|
||||
}
|
||||
|
||||
pub struct Calibration {
|
||||
pub boundaries: Vec<f32>,
|
||||
/// One f16 reconstruction table per level, from level 1 upward.
|
||||
pub books: Vec<Vec<u16>>,
|
||||
}
|
||||
|
||||
/// Fit koference's top-down nested scalar partitions to an already selected,
|
||||
/// normalized sample. Sampling policy and rate selection remain external.
|
||||
pub fn fit_topdown(sample: &[f32], levels: u8) -> Result<Calibration, String> {
|
||||
if !(1..=16).contains(&levels)
|
||||
|| sample.len() < (1usize << levels)
|
||||
|| sample.iter().any(|value| !value.is_finite())
|
||||
{
|
||||
return Err("invalid KAR calibration sample or level count".into());
|
||||
}
|
||||
let mut sorted = sample
|
||||
.iter()
|
||||
.map(|value| f64::from(*value))
|
||||
.collect::<Vec<_>>();
|
||||
sorted.sort_unstable_by(f64::total_cmp);
|
||||
let mut sums = Vec::with_capacity(sorted.len() + 1);
|
||||
let mut squares = Vec::with_capacity(sorted.len() + 1);
|
||||
sums.push(0.0);
|
||||
squares.push(0.0);
|
||||
for value in &sorted {
|
||||
sums.push(sums.last().copied().unwrap() + value);
|
||||
squares.push(squares.last().copied().unwrap() + value * value);
|
||||
}
|
||||
let mut cells = vec![(0usize, sorted.len())];
|
||||
let mut boundaries = Vec::with_capacity((1usize << levels) - 1);
|
||||
for _ in 0..levels {
|
||||
let mut next = Vec::with_capacity(cells.len() * 2);
|
||||
for (lo, hi) in cells {
|
||||
let mut best = None;
|
||||
for middle in lo + 1..hi {
|
||||
if sorted[middle - 1] == sorted[middle] {
|
||||
continue;
|
||||
}
|
||||
let left_count = (middle - lo) as f64;
|
||||
let right_count = (hi - middle) as f64;
|
||||
let left_sum = sums[middle] - sums[lo];
|
||||
let right_sum = sums[hi] - sums[middle];
|
||||
let left_cost = squares[middle] - squares[lo] - left_sum * left_sum / left_count;
|
||||
let right_cost =
|
||||
squares[hi] - squares[middle] - right_sum * right_sum / right_count;
|
||||
let cost = left_cost + right_cost;
|
||||
if best.is_none_or(|(_, previous)| cost < previous) {
|
||||
best = Some((middle, cost));
|
||||
}
|
||||
}
|
||||
let (middle, _) = best.ok_or("KAR calibration sample cannot split every cell")?;
|
||||
boundaries.push(((sorted[middle - 1] + sorted[middle]) / 2.0) as f32);
|
||||
next.push((lo, middle));
|
||||
next.push((middle, hi));
|
||||
}
|
||||
cells = next;
|
||||
}
|
||||
boundaries.sort_unstable_by(f32::total_cmp);
|
||||
if boundaries.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return Err("KAR calibration boundaries collapse in f32".into());
|
||||
}
|
||||
let finest = 1usize << levels;
|
||||
let mut counts = vec![0usize; finest];
|
||||
let mut totals = vec![0f64; finest];
|
||||
for value in &sorted {
|
||||
let index = boundaries.partition_point(|boundary| f64::from(*boundary) < *value);
|
||||
counts[index] += 1;
|
||||
totals[index] += value;
|
||||
}
|
||||
let mut books = vec![Vec::new(); usize::from(levels)];
|
||||
for level in (1..=usize::from(levels)).rev() {
|
||||
books[level - 1] = counts
|
||||
.iter()
|
||||
.zip(&totals)
|
||||
.map(|(count, total)| {
|
||||
f64_to_f16_bits(if *count == 0 {
|
||||
0.0
|
||||
} else {
|
||||
*total / *count as f64
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if level > 1 {
|
||||
counts = counts
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| pair[0] + pair[1])
|
||||
.collect();
|
||||
totals = totals
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| pair[0] + pair[1])
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
Ok(Calibration { boundaries, books })
|
||||
}
|
||||
|
||||
/// Decode a bounded range from a selected KAR prefix. `book` is the f16 table
|
||||
/// for exactly `planes.len()` levels; `start` is a flat element index.
|
||||
pub fn decode_range(
|
||||
scales: &[u16],
|
||||
book: &[u16],
|
||||
planes: &[&[u32]],
|
||||
group: u16,
|
||||
start: usize,
|
||||
output: &mut [f32],
|
||||
) -> Result<(), String> {
|
||||
let group = usize::from(group);
|
||||
if group == 0
|
||||
|| group > 1024
|
||||
|| !group.is_multiple_of(32)
|
||||
|| !(1..=16).contains(&planes.len())
|
||||
|| book.len() != 1usize << planes.len()
|
||||
{
|
||||
return Err("invalid KAR decoder geometry or book".into());
|
||||
}
|
||||
let padded = scales
|
||||
.len()
|
||||
.checked_mul(group)
|
||||
.ok_or("KAR decoder padded size overflow")?;
|
||||
let end = start
|
||||
.checked_add(output.len())
|
||||
.ok_or("KAR decoder range overflow")?;
|
||||
if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) {
|
||||
return Err("KAR decoder range or plane length is invalid".into());
|
||||
}
|
||||
if scales[start / group..end.div_ceil(group)]
|
||||
.iter()
|
||||
.any(|bits| bits & 0x7c00 == 0x7c00)
|
||||
|| book.iter().any(|bits| bits & 0x7c00 == 0x7c00)
|
||||
{
|
||||
return Err("KAR decoder received non-finite f16 data".into());
|
||||
}
|
||||
for (relative, value) in output.iter_mut().enumerate() {
|
||||
let position = start + relative;
|
||||
let mut index = 0usize;
|
||||
for plane in planes {
|
||||
let bit = (plane[position / 32] >> (position % 32)) & 1;
|
||||
index = (index << 1) | bit as usize;
|
||||
}
|
||||
*value = f16_bits_to_f32(book[index]) * f16_bits_to_f32(scales[position / group]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn encode_with_boundaries(
|
||||
weights: &[f32],
|
||||
group: u16,
|
||||
boundaries: &[f32],
|
||||
levels: u8,
|
||||
) -> Result<EncodedPlanes, String> {
|
||||
if !(1..=16).contains(&levels) || boundaries.len() != (1usize << levels) - 1 {
|
||||
return Err("invalid KAR encoder shape or calibration".into());
|
||||
}
|
||||
if boundaries.iter().any(|value| !value.is_finite())
|
||||
|| boundaries.windows(2).any(|pair| pair[0] >= pair[1])
|
||||
{
|
||||
return Err("KAR encoder needs increasing finite boundaries".into());
|
||||
}
|
||||
let normalized = normalize_for_calibration(weights, group)?;
|
||||
let padded = normalized.values.len();
|
||||
let words = padded / 32;
|
||||
let mut planes = vec![vec![0u32; words]; usize::from(levels)];
|
||||
for (position, value) in normalized.values.iter().enumerate() {
|
||||
// NumPy searchsorted defaults to side='left': equality stays in
|
||||
// the lower cell, as in koference's reference encoder.
|
||||
let index = boundaries.partition_point(|boundary| *boundary < *value);
|
||||
for (level, plane) in planes.iter_mut().enumerate() {
|
||||
let bit = (index >> (usize::from(levels) - 1 - level)) & 1;
|
||||
plane[position / 32] |= (bit as u32) << (position % 32);
|
||||
}
|
||||
}
|
||||
Ok(EncodedPlanes {
|
||||
scales: normalized.scales,
|
||||
planes,
|
||||
padded_elements: padded,
|
||||
})
|
||||
}
|
||||
|
||||
// IEEE-754 round-to-nearest, ties-to-even conversion, independent of host
|
||||
// f16 support so the Linux control binary and offline oracle agree.
|
||||
pub fn f32_to_f16_bits(value: f32) -> u16 {
|
||||
let bits = value.to_bits();
|
||||
let sign = ((bits >> 16) & 0x8000) as u16;
|
||||
let exponent = ((bits >> 23) & 0xff) as i32;
|
||||
let mantissa = bits & 0x7f_ffff;
|
||||
if exponent == 255 {
|
||||
return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 };
|
||||
}
|
||||
let half_exponent = exponent - 127 + 15;
|
||||
if half_exponent >= 31 {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if half_exponent <= 0 {
|
||||
if half_exponent < -10 {
|
||||
return sign;
|
||||
}
|
||||
let significand = mantissa | 0x80_0000;
|
||||
let shift = (14 - half_exponent) as u32;
|
||||
let rounded =
|
||||
(significand + ((1u32 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift;
|
||||
return sign | rounded as u16;
|
||||
}
|
||||
let rounded = mantissa + 0x0fff + ((mantissa >> 13) & 1);
|
||||
if rounded & 0x80_0000 != 0 {
|
||||
return sign | (((half_exponent + 1) as u16) << 10);
|
||||
}
|
||||
sign | ((half_exponent as u16) << 10) | ((rounded >> 13) as u16)
|
||||
}
|
||||
|
||||
pub fn f64_to_f16_bits(value: f64) -> u16 {
|
||||
let bits = value.to_bits();
|
||||
let sign = ((bits >> 48) & 0x8000) as u16;
|
||||
let exponent = ((bits >> 52) & 0x7ff) as i32;
|
||||
let mantissa = bits & 0x000f_ffff_ffff_ffff;
|
||||
if exponent == 2047 {
|
||||
return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 };
|
||||
}
|
||||
let half_exponent = exponent - 1023 + 15;
|
||||
if half_exponent >= 31 {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if half_exponent <= 0 {
|
||||
if half_exponent < -10 {
|
||||
return sign;
|
||||
}
|
||||
let significand = mantissa | 0x0010_0000_0000_0000;
|
||||
let shift = (43 - half_exponent) as u32;
|
||||
let rounded =
|
||||
(significand + ((1u64 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift;
|
||||
return sign | rounded as u16;
|
||||
}
|
||||
let rounded = mantissa + 0x0000_01ff_ffff_ffff + ((mantissa >> 42) & 1);
|
||||
if rounded & 0x0010_0000_0000_0000 != 0 {
|
||||
return sign | (((half_exponent + 1) as u16) << 10);
|
||||
}
|
||||
sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16)
|
||||
}
|
||||
|
||||
pub fn f16_bits_to_f32(bits: u16) -> f32 {
|
||||
let sign = (u32::from(bits & 0x8000)) << 16;
|
||||
let exponent = (bits >> 10) & 0x1f;
|
||||
let mantissa = u32::from(bits & 0x03ff);
|
||||
let result = match exponent {
|
||||
0 if mantissa == 0 => sign,
|
||||
0 => {
|
||||
let leading = mantissa.leading_zeros() - 21;
|
||||
let normalized = mantissa << leading;
|
||||
sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13)
|
||||
}
|
||||
31 => sign | 0x7f80_0000 | (mantissa << 13),
|
||||
_ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13),
|
||||
};
|
||||
f32::from_bits(result)
|
||||
}
|
||||
+54
-3
@@ -114,11 +114,62 @@ would cost. Teacher-forced against llama.cpp on `table-igpu` (set2; baseline 8-b
|
||||
| 5 | 76.4% | 0.112 |
|
||||
| 4 | 63.5% | 0.270 |
|
||||
|
||||
Plain block rounding of the attention and output layers is not usable below 8 bits on this model; a 2.5-bit format of that
|
||||
kind (a KAR-style group-32 scale-plus-planes layout is the same rounding) is far outside what the model tolerates. Only
|
||||
calibrated quantization could do better, and that was not tried. The first run of this probe had a half-precision
|
||||
Plain block rounding of the attention and output layers is not usable below 8 bits on this model. (An earlier version of
|
||||
this note called a KAR layout "the same rounding"; it is not: KAR fits a non-uniform codebook per tensor. The real
|
||||
codec was measured afterwards, see the next section.) The first run of this probe had a half-precision
|
||||
conversion bug (small scales flushed to zero); the numbers above are from the fixed code.
|
||||
|
||||
### Experimental quality probe: the real KAR codec on attention, output and expert weights (2026-10-16)
|
||||
|
||||
The KAR codec of the control plane (koference KAR-2: f16 absmax scale per group of 32, then an N-level nested codebook
|
||||
fitted to each tensor by optimal top-down splits) moved unchanged into `crates/kar-codec`, which both the control plane
|
||||
and the CPU runtime use. `LELEKA_EXPERIMENTAL_KAR_LEVELS=N` encodes and decodes the attention and output Q8_0 weights
|
||||
with it (codebook fitted to 65,536 values sampled evenly per tensor) and stores the reconstruction in Q8_0
|
||||
(`LELEKA_EXPERIMENTAL_KAR_TENSORS` selects tensors by name); `LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS=N` with
|
||||
`LELEKA_EXPERIMENTAL_KAR_EXPERT_LAYERS=a-b` does the same for the MXFP4 experts of those layers and stores them in Q8_0.
|
||||
Both are probes only: no speed-up, no serving use. Teacher-forced against llama.cpp on `table-igpu` (set2, 770
|
||||
positions; baseline 8-bit: 93.4% best-token agreement, mean KL 0.016):
|
||||
|
||||
| KAR levels (bits per weight with scale) | attention + output: agreement / mean KL | uniform rounding at the same bits |
|
||||
| --- | --- | --- |
|
||||
| 6 (6.5) | 83.9% / 0.063 | 81.4% / 0.071 |
|
||||
| 5 (5.5) | 79.4% / 0.095 | 76.4% / 0.112 |
|
||||
| 4 (4.5) | 68.1% / 0.213 | 63.5% / 0.270 |
|
||||
| 3 (3.5) | 39.9% / 0.557 | |
|
||||
|
||||
At 4 levels, one group at a time: output layer alone 79.9% / 0.062, `attn_q`+`attn_k` 75.6% / 0.120, `attn_v`+`attn_output`
|
||||
72.6% / 0.172. KAR's codebook is worth about half a bit over uniform rounding, but every group is sensitive on its own,
|
||||
so no mixed-precision split brings attention or the output layer below 8 bits within the gate. (A rebuild in a clean
|
||||
worktree reproduced the 4-level all-tensor run exactly.)
|
||||
|
||||
Experts (already MXFP4, 4.25 bits), layers 0-5 only (a quarter of the model; all 24 in Q8_0 would need about 21 GB):
|
||||
|
||||
| expert format in layers 0-5 | agreement / mean KL |
|
||||
| --- | --- |
|
||||
| Q8_0 copy of the MXFP4 values (control) | 92.5% / 0.018 |
|
||||
| KAR 3 levels (3.5 bits) | 85.8% / 0.081 |
|
||||
| KAR 2 levels (2.5 bits) | 72.9% / 0.166 |
|
||||
|
||||
Four levels cannot be fitted (MXFP4 blocks hold too few distinct values for 16 cells), and they would not save bytes.
|
||||
Even a quarter of the experts at 3.5 bits costs five times the baseline KL, so KAR below MXFP4 is not usable either. With
|
||||
these results no KAR rate saves bytes on gpt-oss-20b within the quality gate; decode stays at 2.56 GB per token.
|
||||
|
||||
### iGPU and NPU prefill at the same time (2026-10-16)
|
||||
|
||||
The two accelerators are separate compute units, and prefill is compute-bound, so running them together adds
|
||||
throughput where decode cannot (`benchmarks/results/igpu-npu-concurrent-prefill-2026-10-16.txt`; `gpu_prefill` and
|
||||
`npu_prefill` examples in separate processes, 2048 synthetic tokens each, two rounds, otherwise idle machine):
|
||||
|
||||
| | iGPU tok/s | NPU tok/s |
|
||||
| --- | --- | --- |
|
||||
| alone | 72.7, 76.5 | 69.8, 74.6 |
|
||||
| both at once | 59.4, 59.0 | 49.3, 46.7 |
|
||||
|
||||
Together they prefilled 4096 tokens in 41.6 and 43.9 s (98 and 93 tok/s), 1.25-1.3x the faster device alone; each slows
|
||||
by a fifth to a third (shared memory and the 15 W power budget). Two requests prefilling at once (one per device) could
|
||||
use this directly; one prompt would need its batches or its expert products split between the devices, which is not
|
||||
built. The figures are an upper bound for such a split: no synchronization between the devices was needed here.
|
||||
|
||||
### Prompt-lookup speculation: measured acceptance on agent-style output (2026-10-15)
|
||||
|
||||
The model (greedy, `run_real`) generated 320 tokens for four agent-style prompts over about 800 tokens of context (a Rust
|
||||
|
||||
Reference in New Issue
Block a user