STRA-338 size-fn2: gptoss, igpu, gptoss-igpu, gptoss-npu and npu-worker tests and examples within the function limits (test fn>30 5 -> 0, 12 -> 0, 1 -> 0, 1 -> 0, 2 -> 0; the igpu gemm WGSL text stays allowlisted); test ids unchanged
This commit is contained in:
@@ -12,41 +12,49 @@ use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let path = std::env::args().nth(1).expect("model path");
|
||||
let path = Path::new(&path);
|
||||
fn load_model(path: &Path) -> Model {
|
||||
let size = std::fs::metadata(path).expect("model file").len();
|
||||
let gguf = Gguf::read(
|
||||
BufReader::with_capacity(1 << 20, File::open(path).expect("open")),
|
||||
size,
|
||||
)
|
||||
.expect("valid GGUF");
|
||||
let model = Model::load(
|
||||
Model::load(
|
||||
std::sync::Arc::new(Mapping::open(path).expect("map model")),
|
||||
&gguf,
|
||||
Dispatch::from_env().expect("kernel level"),
|
||||
4,
|
||||
)
|
||||
.expect("load model");
|
||||
.expect("load model")
|
||||
}
|
||||
|
||||
/// Prefill the prompt with a probe that reports `available` bytes and print what the admission did.
|
||||
fn run_with_memory(label: &str, available: u64, model: &Model, prompt: &[u32]) {
|
||||
let mut accel = GpuPrefill::new()
|
||||
.expect("a GPU")
|
||||
.with_memory_probe(Box::new(move || Some(available)));
|
||||
let admitted = accel.admit(model, prompt.len());
|
||||
let mut state = State::new(&model.config, 64);
|
||||
let reuse = model
|
||||
.prefill_reuse_accelerated(&mut state, prompt, &mut accel, 1, &mut |_, _| true)
|
||||
.expect("prefill")
|
||||
.expect("not cancelled");
|
||||
println!(
|
||||
"{label}: admitted {admitted}, refused so far {}, GPU tokens {}, next token {}",
|
||||
accel.refused(),
|
||||
accel.timings().tokens,
|
||||
reuse.next
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let path = std::env::args().nth(1).expect("model path");
|
||||
let model = load_model(Path::new(&path));
|
||||
let prompt: Vec<u32> = (0..40u32).map(|i| 1000 + i * 37).collect();
|
||||
for (label, available) in [
|
||||
("too little (100 MiB)", 100u64 << 20),
|
||||
("plenty (64 GiB)", 64 << 30),
|
||||
] {
|
||||
let mut accel = GpuPrefill::new()
|
||||
.expect("a GPU")
|
||||
.with_memory_probe(Box::new(move || Some(available)));
|
||||
let admitted = accel.admit(&model, prompt.len());
|
||||
let mut state = State::new(&model.config, 64);
|
||||
let reuse = model
|
||||
.prefill_reuse_accelerated(&mut state, &prompt, &mut accel, 1, &mut |_, _| true)
|
||||
.expect("prefill")
|
||||
.expect("not cancelled");
|
||||
println!(
|
||||
"{label}: admitted {admitted}, refused so far {}, GPU tokens {}, next token {}",
|
||||
accel.refused(),
|
||||
accel.timings().tokens,
|
||||
reuse.next
|
||||
);
|
||||
run_with_memory(label, available, &model, &prompt);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,25 +24,22 @@ fn f16_to_f64(bits: u16) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
if a.len() < 4 {
|
||||
eprintln!("usage: numerics_probe <model.gguf> <openvino root> <service exe> <device,...>");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let path = Path::new(&a[0]);
|
||||
fn load_model(path: &Path) -> Model {
|
||||
let size = std::fs::metadata(path).unwrap().len();
|
||||
let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap();
|
||||
let model = Model::load(
|
||||
Model::load(
|
||||
std::sync::Arc::new(Mapping::open(path).unwrap()),
|
||||
&gguf,
|
||||
Dispatch::from_env().unwrap(),
|
||||
4,
|
||||
)
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The layer-0 normalised hidden states of the tokens, one row each.
|
||||
fn normalised_activations(model: &Model, tokens: &[u32]) -> Vec<f32> {
|
||||
let c = &model.config;
|
||||
let e = c.n_embd;
|
||||
let tokens: Vec<u32> = (0..32).map(|i| 1000 + i * 1237).collect();
|
||||
let view = model.layer_view(0);
|
||||
let mut h = vec![0.0f32; tokens.len() * e];
|
||||
for (t, row) in h.chunks_exact_mut(e).enumerate() {
|
||||
@@ -50,21 +47,16 @@ fn main() {
|
||||
model.embed(tokens[t], &mut x).unwrap();
|
||||
ops::rms_norm(&x, view.attn_norm, c.rms_eps, row);
|
||||
}
|
||||
let max = h.iter().fold(0.0f32, |m, v| m.max(v.abs()));
|
||||
let rms =
|
||||
(h.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / h.len() as f64).sqrt();
|
||||
println!("layer-0 normalised activations: max |h| {max:.2}, rms {rms:.3}");
|
||||
h
|
||||
}
|
||||
|
||||
// f16 inputs, as the device receives them
|
||||
let dispatch = Dispatch::from_env().unwrap();
|
||||
let mut halves = vec![0u16; h.len()];
|
||||
dispatch.f32_to_f16(&h, &mut halves).unwrap();
|
||||
|
||||
// reference: the value projection in f64 (rows of Q8_0 blocks)
|
||||
/// Reference: the value projection in f64 (rows of Q8_0 blocks) over the f16 inputs.
|
||||
fn reference_projection(model: &Model, halves: &[u16], n_tokens: usize) -> Vec<f64> {
|
||||
let view = model.layer_view(0);
|
||||
let w = &view.wv;
|
||||
let (n, k) = (w.rows, w.cols);
|
||||
let row_bytes = k / 32 * 34;
|
||||
let mut reference = vec![0f64; tokens.len() * n];
|
||||
let mut reference = vec![0f64; n_tokens * n];
|
||||
for r in 0..n {
|
||||
let mut row = vec![0f64; k];
|
||||
for (b, block) in w.data[r * row_bytes..(r + 1) * row_bytes]
|
||||
@@ -78,12 +70,85 @@ fn main() {
|
||||
row[b * 32 + j] = scale * f64::from(*q as i8);
|
||||
}
|
||||
}
|
||||
for t in 0..tokens.len() {
|
||||
for t in 0..n_tokens {
|
||||
reference[t * n + r] = (0..k).map(|i| f16_to_f64(halves[t * k + i]) * row[i]).sum();
|
||||
}
|
||||
}
|
||||
let den: f64 = reference.iter().map(|v| v * v).sum();
|
||||
reference
|
||||
}
|
||||
|
||||
/// Run the projection on one device and print the relative rms errors against the reference.
|
||||
fn probe_device(config: &ServiceConfig, halves: &[u16], reference: &[f64], n_tokens: usize) {
|
||||
let n = reference.len() / n_tokens;
|
||||
let den: f64 = reference.iter().map(|v| v * v).sum();
|
||||
let mut client = Client::start(config, 64).unwrap();
|
||||
client.put(client.layout.input_a, halves).unwrap();
|
||||
let (input, out) = (client.layout.input_a, client.layout.out[0]);
|
||||
let shifts = client
|
||||
.product("blk.0.attn_v.weight", None, n_tokens, n, input, out)
|
||||
.unwrap();
|
||||
let y = client.get(out, n_tokens * n).unwrap();
|
||||
let (num, per_token) = device_errors(&y, shifts.as_deref(), reference, n_tokens);
|
||||
println!(
|
||||
"{} ({}): relative rms error {:.2e}; per token median {:.2e}, worst {:.2e}",
|
||||
config.device,
|
||||
client.device_name(),
|
||||
(num / den).sqrt(),
|
||||
per_token[per_token.len() / 2],
|
||||
per_token[per_token.len() - 1]
|
||||
);
|
||||
}
|
||||
|
||||
/// The summed squared error and the sorted per-token relative rms errors of the device output.
|
||||
fn device_errors(
|
||||
y: &[u16],
|
||||
shifts: Option<&[u8]>,
|
||||
reference: &[f64],
|
||||
n_tokens: usize,
|
||||
) -> (f64, Vec<f64>) {
|
||||
let n = reference.len() / n_tokens;
|
||||
let mut num = 0f64;
|
||||
let mut per_token = Vec::new();
|
||||
for t in 0..n_tokens {
|
||||
let (mut tn, mut td) = (0f64, 0f64);
|
||||
for r in 0..n {
|
||||
let shift = shifts.map_or(0, |s| i32::from(s[r]));
|
||||
let d = f16_to_f64(y[t * n + r]) / 2f64.powi(shift) - reference[t * n + r];
|
||||
tn += d * d;
|
||||
td += reference[t * n + r] * reference[t * n + r];
|
||||
}
|
||||
num += tn;
|
||||
per_token.push((tn / td).sqrt());
|
||||
}
|
||||
per_token.sort_by(|x, y| x.total_cmp(y));
|
||||
(num, per_token)
|
||||
}
|
||||
|
||||
fn print_activation_stats(h: &[f32]) {
|
||||
let max = h.iter().fold(0.0f32, |m, v| m.max(v.abs()));
|
||||
let rms =
|
||||
(h.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / h.len() as f64).sqrt();
|
||||
println!("layer-0 normalised activations: max |h| {max:.2}, rms {rms:.3}");
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
if a.len() < 4 {
|
||||
eprintln!("usage: numerics_probe <model.gguf> <openvino root> <service exe> <device,...>");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let path = Path::new(&a[0]);
|
||||
let model = load_model(path);
|
||||
let tokens: Vec<u32> = (0..32).map(|i| 1000 + i * 1237).collect();
|
||||
let h = normalised_activations(&model, &tokens);
|
||||
print_activation_stats(&h);
|
||||
|
||||
// f16 inputs, as the device receives them
|
||||
let dispatch = Dispatch::from_env().unwrap();
|
||||
let mut halves = vec![0u16; h.len()];
|
||||
dispatch.f32_to_f16(&h, &mut halves).unwrap();
|
||||
|
||||
let reference = reference_projection(&model, &halves, tokens.len());
|
||||
for device in a[3].split(',') {
|
||||
let config = ServiceConfig {
|
||||
service: PathBuf::from(&a[2]),
|
||||
@@ -92,33 +157,6 @@ fn main() {
|
||||
model: path.to_path_buf(),
|
||||
cache_dir: None,
|
||||
};
|
||||
let mut client = Client::start(&config, 64).unwrap();
|
||||
client.put(client.layout.input_a, &halves).unwrap();
|
||||
let (input, out) = (client.layout.input_a, client.layout.out[0]);
|
||||
let shifts = client
|
||||
.product("blk.0.attn_v.weight", None, tokens.len(), n, input, out)
|
||||
.unwrap();
|
||||
let y = client.get(out, tokens.len() * n).unwrap();
|
||||
let mut num = 0f64;
|
||||
let mut per_token = Vec::new();
|
||||
for t in 0..tokens.len() {
|
||||
let (mut tn, mut td) = (0f64, 0f64);
|
||||
for r in 0..n {
|
||||
let shift = shifts.as_ref().map_or(0, |s| i32::from(s[r]));
|
||||
let d = f16_to_f64(y[t * n + r]) / 2f64.powi(shift) - reference[t * n + r];
|
||||
tn += d * d;
|
||||
td += reference[t * n + r] * reference[t * n + r];
|
||||
}
|
||||
num += tn;
|
||||
per_token.push((tn / td).sqrt());
|
||||
}
|
||||
per_token.sort_by(|x, y| x.total_cmp(y));
|
||||
println!(
|
||||
"{device} ({}): relative rms error {:.2e}; per token median {:.2e}, worst {:.2e}",
|
||||
client.device_name(),
|
||||
(num / den).sqrt(),
|
||||
per_token[per_token.len() / 2],
|
||||
per_token[per_token.len() - 1]
|
||||
);
|
||||
probe_device(&config, &halves, &reference, tokens.len());
|
||||
}
|
||||
}
|
||||
|
||||
+105
-75
@@ -104,6 +104,14 @@ fn to_bits(values: &[f32]) -> Vec<u16> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One `attend_with_sink` run at one kernel level.
|
||||
fn attend_at(dispatch: &Dispatch, head: Head, kv: KvRows, n: usize) -> Vec<f32> {
|
||||
let mut scores = vec![0.0f32; n.max(1)];
|
||||
let mut out = vec![9.0f32; head.query.len()];
|
||||
attend_with_sink(head, kv, n, dispatch, &mut scores, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `attend_with_sink` at every kernel level this machine supports.
|
||||
fn attend_everywhere(
|
||||
query: &[f32],
|
||||
@@ -120,22 +128,12 @@ fn attend_everywhere(
|
||||
let Ok(dispatch) = Dispatch::with_isa(isa) else {
|
||||
continue;
|
||||
};
|
||||
let mut scores = vec![0.0f32; n.max(1)];
|
||||
let mut out = vec![9.0f32; query.len()];
|
||||
attend_with_sink(
|
||||
Head { query, scale, sink },
|
||||
KvRows {
|
||||
keys: &keys,
|
||||
values: &values,
|
||||
stride,
|
||||
},
|
||||
n,
|
||||
&dispatch,
|
||||
&mut scores,
|
||||
&mut out,
|
||||
)
|
||||
.unwrap();
|
||||
results.push(out);
|
||||
let kv = KvRows {
|
||||
keys: &keys,
|
||||
values: &values,
|
||||
stride,
|
||||
};
|
||||
results.push(attend_at(&dispatch, Head { query, scale, sink }, kv, n));
|
||||
}
|
||||
results
|
||||
}
|
||||
@@ -179,8 +177,7 @@ fn attention_with_a_finite_sink_matches_an_f64_reference() {
|
||||
})
|
||||
.collect();
|
||||
let m = logits.iter().cloned().fold(f64::from(sink), f64::max);
|
||||
let z: f64 =
|
||||
logits.iter().map(|l| (l - m).exp()).sum::<f64>() + (f64::from(sink) - m).exp();
|
||||
let z: f64 = logits.iter().map(|l| (l - m).exp()).sum::<f64>() + (f64::from(sink) - m).exp();
|
||||
for out in attend_everywhere(&q, scale, sink, &kf[3..], &vf[3..], 3, 5) {
|
||||
for d in 0..3 {
|
||||
let expected: f64 = (1..6)
|
||||
@@ -191,59 +188,77 @@ fn attention_with_a_finite_sink_matches_an_f64_reference() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_heads_equals_the_same_heads_one_at_a_time() {
|
||||
let (hd, stride, n, heads) = (64usize, 128usize, 100usize, 4usize);
|
||||
let mut state = 0xABCDu64;
|
||||
let mut rnd = move || {
|
||||
/// xorshift values in `[-spread / 2, spread / 2)`.
|
||||
fn uniform_source(seed: u64, spread: f32) -> impl FnMut() -> f32 {
|
||||
let mut state = seed;
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 3.0
|
||||
};
|
||||
let queries: Vec<f32> = (0..heads * hd).map(|_| rnd()).collect();
|
||||
let sinks: Vec<f32> = (0..heads).map(|_| rnd()).collect();
|
||||
let ks: Vec<f32> = (0..(n - 1) * stride + hd).map(|_| rnd()).collect();
|
||||
let vs: Vec<f32> = (0..(n - 1) * stride + hd).map(|_| rnd()).collect();
|
||||
let (ks, vs) = (to_bits(&ks), to_bits(&vs));
|
||||
for isa in leleka_cpu_kernels::Isa::ALL {
|
||||
let Ok(dispatch) = Dispatch::with_isa(isa) else {
|
||||
continue;
|
||||
};
|
||||
let kv = || KvRows {
|
||||
keys: &ks,
|
||||
values: &vs,
|
||||
stride,
|
||||
};
|
||||
((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * spread
|
||||
}
|
||||
}
|
||||
|
||||
/// Queries, sinks and the half-precision cache of the grouped-heads test.
|
||||
struct GroupCase {
|
||||
queries: Vec<f32>,
|
||||
sinks: Vec<f32>,
|
||||
keys: Vec<u16>,
|
||||
values: Vec<u16>,
|
||||
dims: (usize, usize, usize, usize), // head width, stride, positions, heads
|
||||
}
|
||||
|
||||
impl GroupCase {
|
||||
fn new() -> Self {
|
||||
let (hd, stride, n, heads) = (64usize, 128usize, 100usize, 4usize);
|
||||
let mut rnd = uniform_source(0xABCD, 3.0);
|
||||
let queries: Vec<f32> = (0..heads * hd).map(|_| rnd()).collect();
|
||||
let sinks: Vec<f32> = (0..heads).map(|_| rnd()).collect();
|
||||
let ks: Vec<f32> = (0..(n - 1) * stride + hd).map(|_| rnd()).collect();
|
||||
let vs: Vec<f32> = (0..(n - 1) * stride + hd).map(|_| rnd()).collect();
|
||||
let (keys, values) = (to_bits(&ks), to_bits(&vs));
|
||||
GroupCase {
|
||||
queries,
|
||||
sinks,
|
||||
keys,
|
||||
values,
|
||||
dims: (hd, stride, n, heads),
|
||||
}
|
||||
}
|
||||
|
||||
fn kv(&self) -> KvRows<'_> {
|
||||
KvRows {
|
||||
keys: &self.keys,
|
||||
values: &self.values,
|
||||
stride: self.dims.1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The grouped kernel's output for all heads.
|
||||
fn grouped(&self, dispatch: &Dispatch) -> Vec<f32> {
|
||||
let (hd, _stride, n, heads) = self.dims;
|
||||
let mut grouped = vec![0.0f32; heads * hd];
|
||||
attend_group_with_sink(
|
||||
Group {
|
||||
queries: &queries,
|
||||
sinks: &sinks,
|
||||
scale: 0.125,
|
||||
},
|
||||
kv(),
|
||||
n,
|
||||
&dispatch,
|
||||
&mut vec![0.0; heads * n],
|
||||
&mut grouped,
|
||||
)
|
||||
.unwrap();
|
||||
let group = Group {
|
||||
queries: &self.queries,
|
||||
sinks: &self.sinks,
|
||||
scale: 0.125,
|
||||
};
|
||||
let mut scores = vec![0.0; heads * n];
|
||||
attend_group_with_sink(group, self.kv(), n, dispatch, &mut scores, &mut grouped).unwrap();
|
||||
grouped
|
||||
}
|
||||
|
||||
/// The grouped kernel equals the single-head kernel head by head.
|
||||
fn check(&self, isa: leleka_cpu_kernels::Isa, dispatch: &Dispatch) {
|
||||
let (hd, _stride, n, heads) = self.dims;
|
||||
let grouped = self.grouped(dispatch);
|
||||
for g in 0..heads {
|
||||
let mut single = vec![0.0f32; hd];
|
||||
attend_with_sink(
|
||||
Head {
|
||||
query: &queries[g * hd..(g + 1) * hd],
|
||||
scale: 0.125,
|
||||
sink: sinks[g],
|
||||
},
|
||||
kv(),
|
||||
n,
|
||||
&dispatch,
|
||||
&mut vec![0.0; n],
|
||||
&mut single,
|
||||
)
|
||||
.unwrap();
|
||||
let head = Head {
|
||||
query: &self.queries[g * hd..(g + 1) * hd],
|
||||
scale: 0.125,
|
||||
sink: self.sinks[g],
|
||||
};
|
||||
let single = attend_at(dispatch, head, self.kv(), n);
|
||||
assert_eq!(
|
||||
&grouped[g * hd..(g + 1) * hd],
|
||||
&single[..],
|
||||
@@ -252,17 +267,23 @@ fn a_group_of_heads_equals_the_same_heads_one_at_a_time() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_heads_equals_the_same_heads_one_at_a_time() {
|
||||
let case = GroupCase::new();
|
||||
for isa in leleka_cpu_kernels::Isa::ALL {
|
||||
let Ok(dispatch) = Dispatch::with_isa(isa) else {
|
||||
continue;
|
||||
};
|
||||
case.check(isa, &dispatch);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attention_over_a_realistic_cache_agrees_across_kernel_levels() {
|
||||
// 64-wide heads at the cache stride of a KV head pair, 300 positions
|
||||
let (hd, stride, n) = (64usize, 128usize, 300usize);
|
||||
let mut state = 0x1234_5678u64;
|
||||
let mut rnd = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 4.0
|
||||
};
|
||||
let mut rnd = uniform_source(0x1234_5678, 4.0);
|
||||
let q: Vec<f32> = (0..hd).map(|_| rnd()).collect();
|
||||
let ks: Vec<f32> = round_half(
|
||||
&(0..(n - 1) * stride + hd)
|
||||
@@ -281,7 +302,15 @@ fn attention_over_a_realistic_cache_agrees_across_kernel_levels() {
|
||||
assert!((a - b).abs() < 2e-5 * (1.0 + a.abs()), "{a} vs {b}");
|
||||
}
|
||||
}
|
||||
// against an f64 softmax
|
||||
assert_matches_f64_softmax(&results[0], (&q, &ks, &vs), (hd, stride, n));
|
||||
}
|
||||
|
||||
/// Against an f64 softmax with sink 0.5 and scale 0.125.
|
||||
fn assert_matches_f64_softmax(
|
||||
result: &[f32],
|
||||
(q, ks, vs): (&[f32], &[f32], &[f32]),
|
||||
(hd, stride, n): (usize, usize, usize),
|
||||
) {
|
||||
let scale = 0.125f64;
|
||||
let logits: Vec<f64> = (0..n)
|
||||
.map(|i| {
|
||||
@@ -298,11 +327,12 @@ fn attention_over_a_realistic_cache_agrees_across_kernel_levels() {
|
||||
.map(|i| (logits[i] - m).exp() / z * f64::from(vs[i * stride + j]))
|
||||
.sum();
|
||||
assert!(
|
||||
(f64::from(results[0][j]) - expected).abs() < 1e-4 * (1.0 + expected.abs()),
|
||||
(f64::from(result[j]) - expected).abs() < 1e-4 * (1.0 + expected.abs()),
|
||||
"column {j}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routing_picks_the_largest_logits_and_softmaxes_only_those() {
|
||||
let logits = [0.1f32, 2.0, -1.0, 2.0, 0.5, 1.0];
|
||||
|
||||
+23
-16
@@ -2,9 +2,8 @@
|
||||
|
||||
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
|
||||
/// Pseudo-random Q8_0 blocks with varied scales.
|
||||
fn random_q8_0_blocks() -> Vec<u8> {
|
||||
let mut s = 0x2545_F491_4F6C_DD1Du64;
|
||||
let mut next = || {
|
||||
s ^= s << 13;
|
||||
@@ -17,22 +16,30 @@ fn the_kar_probe_loses_less_with_more_levels_and_keeps_q8_0_layout() {
|
||||
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);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The dequantized values of Q8_0 blocks.
|
||||
fn q8_0_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()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kar_probe_loses_less_with_more_levels_and_keeps_q8_0_layout() {
|
||||
let bytes = random_q8_0_blocks();
|
||||
let original = q8_0_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 got = q8_0_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()
|
||||
|
||||
@@ -116,34 +116,41 @@ fn chunked_prefill_is_bit_identical_to_feeding_tokens_one_at_a_time() {
|
||||
let gguf = Gguf::read(&w.file[..], w.file.len() as u64).unwrap();
|
||||
let tokens = [5u32, 17, 3, 42, 9, 60, 11, 30, 2, 71, 8];
|
||||
for threads in [1usize, 3] {
|
||||
let mut model = Model::load(std::sync::Arc::new(w.file.clone()), &gguf, Dispatch::best(), threads).unwrap();
|
||||
let weights = std::sync::Arc::new(w.file.clone());
|
||||
let mut model = Model::load(weights, &gguf, Dispatch::best(), threads).unwrap();
|
||||
let (mut seq, seq_next) = feed_one_at_a_time(&model, &tokens);
|
||||
// the continuation after the prompt exercises the cache the prefill filled
|
||||
let seq_after = model.forward(&mut seq, 13, tokens.len()).unwrap();
|
||||
for chunk in [1usize, 2, 3, 4, 11, 64] {
|
||||
model.set_prefill_chunk(chunk);
|
||||
let mut st = State::new(&model.config, 16);
|
||||
let next = model.prefill(&mut st, &tokens, 0).unwrap();
|
||||
assert_eq!(next, Some(seq_next), "chunk {chunk} threads {threads}");
|
||||
let prefill_logits = st.logits.clone();
|
||||
let after = model.forward(&mut st, 13, tokens.len()).unwrap();
|
||||
assert_eq!(after, seq_after, "chunk {chunk} threads {threads}");
|
||||
assert_eq!(
|
||||
bits(&st.logits),
|
||||
bits(&seq.logits),
|
||||
"logits after the continuation, chunk {chunk} threads {threads}"
|
||||
);
|
||||
// logits right after the prefill, against a fresh sequential run of the same tokens
|
||||
let (again, _) = feed_one_at_a_time(&model, &tokens);
|
||||
assert_eq!(
|
||||
bits(&prefill_logits),
|
||||
bits(&again.logits),
|
||||
"logits after the prefill, chunk {chunk} threads {threads}"
|
||||
);
|
||||
let sequential = (&seq, seq_next, seq_after);
|
||||
check_chunk(&model, &tokens, sequential, format!("chunk {chunk} threads {threads}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One prefill chunk size against the sequential run: next token, continuation and logits.
|
||||
fn check_chunk(model: &Model, tokens: &[u32], (seq, seq_next, seq_after): (&State, u32, u32), ctx: String) {
|
||||
let mut st = State::new(&model.config, 16);
|
||||
let next = model.prefill(&mut st, tokens, 0).unwrap();
|
||||
assert_eq!(next, Some(seq_next), "{ctx}");
|
||||
let prefill_logits = st.logits.clone();
|
||||
let after = model.forward(&mut st, 13, tokens.len()).unwrap();
|
||||
assert_eq!(after, seq_after, "{ctx}");
|
||||
assert_eq!(
|
||||
bits(&st.logits),
|
||||
bits(&seq.logits),
|
||||
"logits after the continuation, {ctx}"
|
||||
);
|
||||
// logits right after the prefill, against a fresh sequential run of the same tokens
|
||||
let (again, _) = feed_one_at_a_time(model, tokens);
|
||||
assert_eq!(
|
||||
bits(&prefill_logits),
|
||||
bits(&again.logits),
|
||||
"logits after the prefill, {ctx}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefill_can_resume_after_an_earlier_prefix() {
|
||||
let w = build_world(10);
|
||||
|
||||
@@ -3,48 +3,62 @@
|
||||
//!
|
||||
//! Reports milliseconds for one layer's attention over a batch of `m` tokens ending at position `end`.
|
||||
|
||||
use leleka_igpu::{AttentionShape, Gpu};
|
||||
use leleka_igpu::{AttentionShape, Buf, Gpu};
|
||||
|
||||
/// Time five runs of one layer's attention over a batch of `m` tokens ending at `end`.
|
||||
fn time_case(gpu: &Gpu, caches: &Caches, (end, m, window): (usize, usize, usize)) {
|
||||
let (kw, qw) = (512usize, 4096usize);
|
||||
let q = gpu.zeros(m * qw);
|
||||
let out = gpu.zeros(m * qw);
|
||||
let shape = AttentionShape {
|
||||
m,
|
||||
pos0: end - m,
|
||||
window,
|
||||
kv_width: kw,
|
||||
q_width: qw,
|
||||
scale: 0.125,
|
||||
};
|
||||
let run = |count: usize| {
|
||||
let mut rec = gpu.recorder();
|
||||
for _ in 0..count {
|
||||
rec.attention(shape, &q, &caches.k, &caches.v, &caches.sinks, &out)
|
||||
.unwrap();
|
||||
}
|
||||
rec.submit().unwrap();
|
||||
};
|
||||
run(1);
|
||||
let start = std::time::Instant::now();
|
||||
run(5);
|
||||
println!(
|
||||
"{end:>6} {m:>6} {window:>7} {:>10.2}",
|
||||
start.elapsed().as_secs_f64() / 5.0 * 1e3
|
||||
);
|
||||
}
|
||||
|
||||
/// The key and value caches and the sinks the cases share.
|
||||
struct Caches {
|
||||
k: Buf,
|
||||
v: Buf,
|
||||
sinks: Buf,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let gpu = Gpu::new().expect("a GPU");
|
||||
println!("adapter: {}", gpu.adapter_name());
|
||||
let (kw, qw) = (512usize, 4096usize);
|
||||
let cap = 8192usize;
|
||||
let kcache = gpu.zeros(cap * kw / 2);
|
||||
let vcache = gpu.zeros(cap * kw / 2);
|
||||
let sinks = gpu.zeros(64);
|
||||
let (kw, cap) = (512usize, 8192usize);
|
||||
let caches = Caches {
|
||||
k: gpu.zeros(cap * kw / 2),
|
||||
v: gpu.zeros(cap * kw / 2),
|
||||
sinks: gpu.zeros(64),
|
||||
};
|
||||
println!("{:>6} {:>6} {:>7} {:>10}", "end", "m", "window", "ms");
|
||||
for (end, m, window) in [
|
||||
for case in [
|
||||
(512usize, 512usize, 0usize),
|
||||
(2048, 512, 0),
|
||||
(4096, 512, 0),
|
||||
(4096, 512, 128),
|
||||
(8192, 512, 0),
|
||||
] {
|
||||
let q = gpu.zeros(m * qw);
|
||||
let out = gpu.zeros(m * qw);
|
||||
let shape = AttentionShape {
|
||||
m,
|
||||
pos0: end - m,
|
||||
window,
|
||||
kv_width: kw,
|
||||
q_width: qw,
|
||||
scale: 0.125,
|
||||
};
|
||||
let run = |count: usize| {
|
||||
let mut rec = gpu.recorder();
|
||||
for _ in 0..count {
|
||||
rec.attention(shape, &q, &kcache, &vcache, &sinks, &out)
|
||||
.unwrap();
|
||||
}
|
||||
rec.submit().unwrap();
|
||||
};
|
||||
run(1);
|
||||
let start = std::time::Instant::now();
|
||||
run(5);
|
||||
println!(
|
||||
"{end:>6} {m:>6} {window:>7} {:>10.2}",
|
||||
start.elapsed().as_secs_f64() / 5.0 * 1e3
|
||||
);
|
||||
time_case(&gpu, &caches, case);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
}
|
||||
"#;
|
||||
|
||||
fn main() {
|
||||
fn request_device() -> (wgpu::Device, wgpu::Queue) {
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
@@ -47,25 +47,30 @@ fn main() {
|
||||
}))
|
||||
.expect("an adapter");
|
||||
println!("adapter: {}", adapter.get_info().name);
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
required_limits: adapter.limits(),
|
||||
..Default::default()
|
||||
}))
|
||||
.expect("device");
|
||||
.expect("device")
|
||||
}
|
||||
|
||||
fn build_pipeline(device: &wgpu::Device) -> wgpu::ComputePipeline {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let threads = 1 << 18;
|
||||
let iters = 4096u32;
|
||||
})
|
||||
}
|
||||
|
||||
/// The output storage buffer and the uniform buffer with the iteration count.
|
||||
fn buffers(device: &wgpu::Device, (threads, iters): (u64, u32)) -> (wgpu::Buffer, wgpu::Buffer) {
|
||||
let out = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: threads * 4,
|
||||
@@ -77,7 +82,16 @@ fn main() {
|
||||
contents: bytemuck::cast_slice(&[iters, 0u32, 0, 0]),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
(out, params)
|
||||
}
|
||||
|
||||
fn build_bind_group(
|
||||
device: &wgpu::Device,
|
||||
pipeline: &wgpu::ComputePipeline,
|
||||
(threads, iters): (u64, u32),
|
||||
) -> wgpu::BindGroup {
|
||||
let (out, params) = buffers(device, (threads, iters));
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
@@ -90,7 +104,15 @@ fn main() {
|
||||
resource: params.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let (device, queue) = request_device();
|
||||
let pipeline = build_pipeline(&device);
|
||||
let threads = 1 << 18;
|
||||
let iters = 4096u32;
|
||||
let bind = build_bind_group(&device, &pipeline, (threads, iters));
|
||||
let run = |count: usize| {
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
for _ in 0..count {
|
||||
|
||||
@@ -4,31 +4,101 @@
|
||||
//! Reports milliseconds per product and the integer throughput (2 * m * n * k operations).
|
||||
|
||||
use leleka_cpu_kernels::Dispatch;
|
||||
use leleka_igpu::{Gpu, WeightKind};
|
||||
use leleka_igpu::{Gpu, GpuActivations, GpuMatrix, WeightKind};
|
||||
|
||||
fn main() {
|
||||
// LELEKA_IGPU_TILE=TMxTN picks the outputs per thread (default 4x4, the measured best)
|
||||
let (tm, tn) = std::env::var("LELEKA_IGPU_TILE")
|
||||
/// LELEKA_IGPU_TILE=TMxTN picks the outputs per thread (default 4x4, the measured best)
|
||||
fn tile_from_env() -> (u32, u32) {
|
||||
std::env::var("LELEKA_IGPU_TILE")
|
||||
.ok()
|
||||
.and_then(|s| {
|
||||
s.split_once('x')
|
||||
.map(|(a, b)| (a.parse().ok(), b.parse().ok()))
|
||||
})
|
||||
.and_then(|(a, b)| Some((a?, b?)))
|
||||
.unwrap_or((4, 4));
|
||||
.unwrap_or((4, 4))
|
||||
}
|
||||
|
||||
fn xorshift(mut seed: u64) -> impl FnMut() -> u64 {
|
||||
move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
}
|
||||
}
|
||||
|
||||
/// Random weights of `n` rows of `blocks` blocks in the given format.
|
||||
fn random_weights(
|
||||
kind: WeightKind,
|
||||
n: usize,
|
||||
blocks: usize,
|
||||
next: &mut impl FnMut() -> u64,
|
||||
) -> Vec<u8> {
|
||||
match kind {
|
||||
WeightKind::Q8_0 => (0..n * blocks)
|
||||
.flat_map(|_| {
|
||||
let mut b = vec![0x00, 0x2C]; // half 0.0625
|
||||
b.extend((0..32).map(|_| next() as u8));
|
||||
b
|
||||
})
|
||||
.collect(),
|
||||
WeightKind::Mxfp4 => (0..n * blocks)
|
||||
.flat_map(|_| {
|
||||
let mut b = vec![120u8];
|
||||
b.extend((0..16).map(|_| next() as u8));
|
||||
b
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Median seconds of five timings of the product.
|
||||
fn median_seconds(gpu: &Gpu, wm: &GpuMatrix, am: &GpuActivations) -> f64 {
|
||||
let mut times: Vec<f64> = (0..5)
|
||||
.map(|_| gpu.time_matmul(wm, am, 10).expect("run"))
|
||||
.collect();
|
||||
times.sort_by(|a, b| a.total_cmp(b));
|
||||
times[2]
|
||||
}
|
||||
|
||||
/// Time `m` activation rows against the uploaded weights; prints one row.
|
||||
fn time_product(
|
||||
gpu: &Gpu,
|
||||
wm: &GpuMatrix,
|
||||
(kind, n, m): (WeightKind, usize, usize),
|
||||
next: &mut impl FnMut() -> u64,
|
||||
) {
|
||||
let blocks = 90;
|
||||
let x: Vec<f32> = (0..m * blocks * 32)
|
||||
.map(|_| (next() % 1000) as f32 / 100.0 - 5.0)
|
||||
.collect();
|
||||
let mut q = vec![0u8; m * blocks * 34];
|
||||
Dispatch::best()
|
||||
.quantize_q8_0(&x, &mut q)
|
||||
.expect("quantize");
|
||||
let am = gpu
|
||||
.upload_activations(m, blocks * 32, &q)
|
||||
.expect("upload activations");
|
||||
let t = median_seconds(gpu, wm, &am);
|
||||
let ops = 2.0 * m as f64 * n as f64 * (blocks * 32) as f64;
|
||||
println!(
|
||||
"{:<8} {:>5} {:>6} {:>10.3} {:>9.2}",
|
||||
format!("{kind:?}"),
|
||||
m,
|
||||
n,
|
||||
t * 1e3,
|
||||
ops / t / 1e12
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let (tm, tn) = tile_from_env();
|
||||
let gpu = Gpu::with_tile(tm, tn).expect("a GPU");
|
||||
println!(
|
||||
"adapter: {}, tile {tm}x{tn} outputs per thread",
|
||||
gpu.adapter_name()
|
||||
);
|
||||
let d = Dispatch::best();
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
let mut next = xorshift(0x9E37_79B9_7F4A_7C15u64);
|
||||
let blocks = 90; // K = 2880, gpt-oss' hidden size
|
||||
println!(
|
||||
"{:<8} {:>5} {:>6} {:>10} {:>9}",
|
||||
@@ -40,46 +110,10 @@ fn main() {
|
||||
(WeightKind::Q8_0, 4096),
|
||||
(WeightKind::Q8_0, 2880),
|
||||
] {
|
||||
let w: Vec<u8> = match kind {
|
||||
WeightKind::Q8_0 => (0..n * blocks)
|
||||
.flat_map(|_| {
|
||||
let mut b = vec![0x00, 0x2C]; // half 0.0625
|
||||
b.extend((0..32).map(|_| next() as u8));
|
||||
b
|
||||
})
|
||||
.collect(),
|
||||
WeightKind::Mxfp4 => (0..n * blocks)
|
||||
.flat_map(|_| {
|
||||
let mut b = vec![120u8];
|
||||
b.extend((0..16).map(|_| next() as u8));
|
||||
b
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let w = random_weights(kind, n, blocks, &mut next);
|
||||
let wm = gpu.upload_matrix(kind, n, blocks * 32, &w).expect("upload");
|
||||
for m in [8usize, 16, 32, 64, 128, 256] {
|
||||
let x: Vec<f32> = (0..m * blocks * 32)
|
||||
.map(|_| (next() % 1000) as f32 / 100.0 - 5.0)
|
||||
.collect();
|
||||
let mut q = vec![0u8; m * blocks * 34];
|
||||
d.quantize_q8_0(&x, &mut q).expect("quantize");
|
||||
let am = gpu
|
||||
.upload_activations(m, blocks * 32, &q)
|
||||
.expect("upload activations");
|
||||
let mut times: Vec<f64> = (0..5)
|
||||
.map(|_| gpu.time_matmul(&wm, &am, 10).expect("run"))
|
||||
.collect();
|
||||
times.sort_by(|a, b| a.total_cmp(b));
|
||||
let t = times[2];
|
||||
let ops = 2.0 * m as f64 * n as f64 * (blocks * 32) as f64;
|
||||
println!(
|
||||
"{:<8} {:>5} {:>6} {:>10.3} {:>9.2}",
|
||||
format!("{kind:?}"),
|
||||
m,
|
||||
n,
|
||||
t * 1e3,
|
||||
ops / t / 1e12
|
||||
);
|
||||
time_product(&gpu, &wm, (kind, n, m), &mut next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+40
-24
@@ -40,41 +40,57 @@ fn activations_get_float_scales() {
|
||||
assert_eq!(quants.len(), 8);
|
||||
}
|
||||
|
||||
/// The straightforward definitions, to check the threaded repackers against on inputs large enough to be
|
||||
/// split (ragged sizes included).
|
||||
#[test]
|
||||
fn threaded_repacking_equals_the_plain_definition() {
|
||||
let mut seed = 0x1234_5678_9ABC_DEF1u64;
|
||||
let mut next = move || {
|
||||
fn xorshift_bytes(seed: u64) -> impl FnMut() -> u8 {
|
||||
let mut seed = seed;
|
||||
move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed as u8
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// The straightforward Q8_0 definition: the quants as words, the half scales packed in pairs.
|
||||
fn plain_q8_0(q8: &[u8]) -> (Vec<u32>, Vec<u32>) {
|
||||
let mut want_q = Vec::new();
|
||||
let mut halves = Vec::new();
|
||||
for b in q8.as_chunks::<Q8_0_BYTES>().0 {
|
||||
halves.push(u16::from_le_bytes([b[0], b[1]]));
|
||||
want_q.extend(le_words(&b[2..]));
|
||||
}
|
||||
let want_s: Vec<u32> = halves
|
||||
.chunks(2)
|
||||
.map(|p| u32::from(p[0]) | (u32::from(*p.get(1).unwrap_or(&0)) << 16))
|
||||
.collect();
|
||||
(want_q, want_s)
|
||||
}
|
||||
|
||||
/// The straightforward MXFP4 definition: the nibbles as words, the exponents packed as words.
|
||||
fn plain_mxfp4(mx: &[u8]) -> (Vec<u32>, Vec<u32>) {
|
||||
let mut want_n = Vec::new();
|
||||
let mut want_e = Vec::new();
|
||||
for b in mx.as_chunks::<MXFP4_BYTES>().0 {
|
||||
want_e.push(b[0]);
|
||||
want_n.extend(le_words(&b[1..]));
|
||||
}
|
||||
(want_n, le_words(&want_e))
|
||||
}
|
||||
|
||||
/// The straightforward definitions, to check the threaded repackers against on inputs large enough to be
|
||||
/// split (ragged sizes included).
|
||||
#[test]
|
||||
fn threaded_repacking_equals_the_plain_definition() {
|
||||
let mut next = xorshift_bytes(0x1234_5678_9ABC_DEF1u64);
|
||||
for n in [20_000usize, 40_001, 65_536 + 3] {
|
||||
let q8: Vec<u8> = (0..n * Q8_0_BYTES).map(|_| next()).collect();
|
||||
let (quants, scales) = repack_q8_0(&q8);
|
||||
let mut want_q = Vec::new();
|
||||
let mut halves = Vec::new();
|
||||
for b in q8.as_chunks::<Q8_0_BYTES>().0 {
|
||||
halves.push(u16::from_le_bytes([b[0], b[1]]));
|
||||
want_q.extend(le_words(&b[2..]));
|
||||
}
|
||||
let want_s: Vec<u32> = halves
|
||||
.chunks(2)
|
||||
.map(|p| u32::from(p[0]) | (u32::from(*p.get(1).unwrap_or(&0)) << 16))
|
||||
.collect();
|
||||
let (want_q, want_s) = plain_q8_0(&q8);
|
||||
assert!(quants == want_q && scales == want_s, "q8_0, {n} blocks");
|
||||
|
||||
let mx: Vec<u8> = (0..n * MXFP4_BYTES).map(|_| next()).collect();
|
||||
let (nibbles, exponents) = repack_mxfp4(&mx);
|
||||
let mut want_n = Vec::new();
|
||||
let mut want_e = Vec::new();
|
||||
for b in mx.as_chunks::<MXFP4_BYTES>().0 {
|
||||
want_e.push(b[0]);
|
||||
want_n.extend(le_words(&b[1..]));
|
||||
}
|
||||
assert!(nibbles == want_n && exponents == le_words(&want_e), "mxfp4, {n} blocks");
|
||||
let (want_n, want_e) = plain_mxfp4(&mx);
|
||||
assert!(nibbles == want_n && exponents == want_e, "mxfp4, {n} blocks");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+108
-69
@@ -110,82 +110,121 @@ fn kv_store_rounds_to_half_like_the_cpu() {
|
||||
assert!(words[(pos0 + m) * kw / 2..].iter().all(|w| *w == 0));
|
||||
}
|
||||
|
||||
fn attention_case(gpu: &Gpu, pos0: usize, m: usize, window: usize, seed: u64) {
|
||||
let d = Dispatch::best();
|
||||
let (kv_heads, group, hd) = (2usize, 8usize, 64usize);
|
||||
let (kw, qw) = (kv_heads * hd, kv_heads * group * hd);
|
||||
const KV_HEADS: usize = 2;
|
||||
const GROUP: usize = 8;
|
||||
const HD: usize = 64;
|
||||
const KW: usize = KV_HEADS * HD;
|
||||
const QW: usize = KV_HEADS * GROUP * HD;
|
||||
|
||||
/// Random queries, sinks and the half-precision cache of one attention case.
|
||||
struct AttnData {
|
||||
pos0: usize,
|
||||
q: Vec<f32>,
|
||||
sinks: Vec<f32>,
|
||||
kh: Vec<u16>,
|
||||
vh: Vec<u16>,
|
||||
kwords: Vec<u32>,
|
||||
vwords: Vec<u32>,
|
||||
}
|
||||
|
||||
fn attention_data(d: &Dispatch, (pos0, m): (usize, usize), seed: u64) -> AttnData {
|
||||
let positions = pos0 + m;
|
||||
let mut rng = Rng(seed);
|
||||
let q: Vec<f32> = (0..m * qw).map(|_| rng.unit() * 1.5).collect();
|
||||
let k: Vec<f32> = (0..positions * kw).map(|_| rng.unit() * 1.5).collect();
|
||||
let v: Vec<f32> = (0..positions * kw).map(|_| rng.unit()).collect();
|
||||
let sinks: Vec<f32> = (0..kv_heads * group).map(|_| rng.unit() * 2.0).collect();
|
||||
let (kh, kwords) = pack_halves(&d, &k);
|
||||
let (vh, vwords) = pack_halves(&d, &v);
|
||||
let q: Vec<f32> = (0..m * QW).map(|_| rng.unit() * 1.5).collect();
|
||||
let k: Vec<f32> = (0..positions * KW).map(|_| rng.unit() * 1.5).collect();
|
||||
let v: Vec<f32> = (0..positions * KW).map(|_| rng.unit()).collect();
|
||||
let sinks: Vec<f32> = (0..KV_HEADS * GROUP).map(|_| rng.unit() * 2.0).collect();
|
||||
let (kh, kwords) = pack_halves(d, &k);
|
||||
let (vh, vwords) = pack_halves(d, &v);
|
||||
AttnData {
|
||||
pos0,
|
||||
q,
|
||||
sinks,
|
||||
kh,
|
||||
vh,
|
||||
kwords,
|
||||
vwords,
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU attention output for the case.
|
||||
fn gpu_attention(gpu: &Gpu, data: &AttnData, (pos0, m, window): (usize, usize, usize)) -> Vec<f32> {
|
||||
let (qb, kb, vb, sb) = (
|
||||
gpu.buf_f32(&q),
|
||||
gpu.buf_u32(&kwords),
|
||||
gpu.buf_u32(&vwords),
|
||||
gpu.buf_f32(&sinks),
|
||||
gpu.buf_f32(&data.q),
|
||||
gpu.buf_u32(&data.kwords),
|
||||
gpu.buf_u32(&data.vwords),
|
||||
gpu.buf_f32(&data.sinks),
|
||||
);
|
||||
let out = gpu.zeros(m * qw);
|
||||
let scale = 1.0 / (hd as f32).sqrt();
|
||||
let out = gpu.zeros(m * QW);
|
||||
let scale = 1.0 / (HD as f32).sqrt();
|
||||
let mut rec = gpu.recorder();
|
||||
rec.attention(
|
||||
AttentionShape {
|
||||
m,
|
||||
pos0,
|
||||
window,
|
||||
kv_width: kw,
|
||||
q_width: qw,
|
||||
scale,
|
||||
},
|
||||
&qb,
|
||||
&kb,
|
||||
&vb,
|
||||
&sb,
|
||||
&out,
|
||||
)
|
||||
.unwrap();
|
||||
let shape = AttentionShape {
|
||||
m,
|
||||
pos0,
|
||||
window,
|
||||
kv_width: KW,
|
||||
q_width: QW,
|
||||
scale,
|
||||
};
|
||||
rec.attention(shape, &qb, &kb, &vb, &sb, &out).unwrap();
|
||||
rec.submit().unwrap();
|
||||
let got = gpu.read_f32(&out).unwrap();
|
||||
gpu.read_f32(&out).unwrap()
|
||||
}
|
||||
|
||||
/// The CPU reference for token `t`, KV head `kvh`: its output row.
|
||||
fn cpu_head(d: &Dispatch, data: &AttnData, window: usize, pos: usize, kvh: usize) -> Vec<f32> {
|
||||
let scale = 1.0 / (HD as f32).sqrt();
|
||||
let first = if window != 0 {
|
||||
(pos + 1).saturating_sub(window)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let attended = pos + 1 - first;
|
||||
let mut scores = vec![0.0f32; GROUP * attended];
|
||||
let mut want = vec![0.0f32; GROUP * HD];
|
||||
let start = first * KW + kvh * HD;
|
||||
let qs = (pos - data.pos0) * QW + kvh * GROUP * HD;
|
||||
let queries = Group {
|
||||
queries: &data.q[qs..qs + GROUP * HD],
|
||||
sinks: &data.sinks[kvh * GROUP..(kvh + 1) * GROUP],
|
||||
scale,
|
||||
};
|
||||
let kv = KvRows {
|
||||
keys: &data.kh[start..],
|
||||
values: &data.vh[start..],
|
||||
stride: KW,
|
||||
};
|
||||
ops::attend_group_with_sink(queries, kv, attended, d, &mut scores, &mut want).unwrap();
|
||||
want
|
||||
}
|
||||
|
||||
/// The GPU output of token `t`, KV head `kvh` against the CPU reference.
|
||||
fn check_head(
|
||||
d: &Dispatch,
|
||||
data: &AttnData,
|
||||
got: &[f32],
|
||||
case: (usize, usize, usize),
|
||||
(t, kvh): (usize, usize),
|
||||
) {
|
||||
let (pos0, m, window) = case;
|
||||
let want = cpu_head(d, data, window, pos0 + t, kvh);
|
||||
let qs = t * QW + kvh * GROUP * HD;
|
||||
for (i, w) in want.iter().enumerate() {
|
||||
let g = got[qs + i];
|
||||
assert!(
|
||||
(g - w).abs() <= 2e-5 * (1.0 + w.abs()),
|
||||
"pos0 {pos0} m {m} window {window}: token {t} kv head {kvh} element {i}: gpu {g} vs cpu {w}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn attention_case(gpu: &Gpu, pos0: usize, m: usize, window: usize, seed: u64) {
|
||||
let d = Dispatch::best();
|
||||
let data = attention_data(&d, (pos0, m), seed);
|
||||
let got = gpu_attention(gpu, &data, (pos0, m, window));
|
||||
for t in 0..m {
|
||||
let pos = pos0 + t;
|
||||
let first = if window != 0 {
|
||||
(pos + 1).saturating_sub(window)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let attended = pos + 1 - first;
|
||||
for kvh in 0..kv_heads {
|
||||
let mut scores = vec![0.0f32; group * attended];
|
||||
let mut want = vec![0.0f32; group * hd];
|
||||
let start = first * kw + kvh * hd;
|
||||
let qs = t * qw + kvh * group * hd;
|
||||
ops::attend_group_with_sink(
|
||||
Group {
|
||||
queries: &q[qs..qs + group * hd],
|
||||
sinks: &sinks[kvh * group..(kvh + 1) * group],
|
||||
scale,
|
||||
},
|
||||
KvRows {
|
||||
keys: &kh[start..],
|
||||
values: &vh[start..],
|
||||
stride: kw,
|
||||
},
|
||||
attended,
|
||||
&d,
|
||||
&mut scores,
|
||||
&mut want,
|
||||
)
|
||||
.unwrap();
|
||||
for (i, w) in want.iter().enumerate() {
|
||||
let g = got[qs + i];
|
||||
assert!(
|
||||
(g - w).abs() <= 2e-5 * (1.0 + w.abs()),
|
||||
"pos0 {pos0} m {m} window {window}: token {t} kv head {kvh} element {i}: gpu {g} vs cpu {w}"
|
||||
);
|
||||
}
|
||||
for kvh in 0..KV_HEADS {
|
||||
check_head(&d, &data, &got, (pos0, m, window), (t, kvh));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+92
-46
@@ -61,6 +61,39 @@ fn quantize(d: &Dispatch, rng: &mut Rng, m: usize, blocks: usize) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The exact value (and the sum of the term magnitudes) of one output: the integer block sums combined with
|
||||
/// the block scales in f64.
|
||||
fn exact_output(
|
||||
d: &Dispatch,
|
||||
kind: WeightKind,
|
||||
arow: &[u8],
|
||||
wrow: &[u8],
|
||||
sums: &mut [i32],
|
||||
) -> (f64, f64) {
|
||||
match kind {
|
||||
WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, sums).unwrap(),
|
||||
WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, sums).unwrap(),
|
||||
}
|
||||
let (mut exact, mut magnitude) = (0f64, 0f64);
|
||||
for b in 0..sums.len() {
|
||||
let sa = f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
arow[b * 34],
|
||||
arow[b * 34 + 1],
|
||||
])));
|
||||
let sw = match kind {
|
||||
WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
wrow[b * 34],
|
||||
wrow[b * 34 + 1],
|
||||
]))),
|
||||
WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])),
|
||||
};
|
||||
let term = f64::from(sums[b]) * sa * sw;
|
||||
exact += term;
|
||||
magnitude += term.abs();
|
||||
}
|
||||
(exact, magnitude)
|
||||
}
|
||||
|
||||
fn check(gpu: &Gpu, kind: WeightKind, m: usize, n: usize, blocks: usize, seed: u64) {
|
||||
let d = Dispatch::best();
|
||||
let mut rng = Rng(seed);
|
||||
@@ -78,27 +111,7 @@ fn check(gpu: &Gpu, kind: WeightKind, m: usize, n: usize, blocks: usize, seed: u
|
||||
let arow = &a[i * blocks * 34..(i + 1) * blocks * 34];
|
||||
for j in 0..n {
|
||||
let wrow = &w[j * blocks * block_bytes..(j + 1) * blocks * block_bytes];
|
||||
match kind {
|
||||
WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(),
|
||||
WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(),
|
||||
}
|
||||
let (mut exact, mut magnitude) = (0f64, 0f64);
|
||||
for b in 0..blocks {
|
||||
let sa = f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
arow[b * 34],
|
||||
arow[b * 34 + 1],
|
||||
])));
|
||||
let sw = match kind {
|
||||
WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
wrow[b * 34],
|
||||
wrow[b * 34 + 1],
|
||||
]))),
|
||||
WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])),
|
||||
};
|
||||
let term = f64::from(sums[b]) * sa * sw;
|
||||
exact += term;
|
||||
magnitude += term.abs();
|
||||
}
|
||||
let (exact, magnitude) = exact_output(&d, kind, arow, wrow, &mut sums);
|
||||
let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23);
|
||||
let error = (f64::from(got[i * n + j]) - exact).abs();
|
||||
assert!(
|
||||
@@ -178,6 +191,54 @@ fn shapes_that_do_not_fit_are_refused_without_touching_the_gpu_state() {
|
||||
assert!(w.cols() == 64 && w.rows() == 1 && a.rows() == 1);
|
||||
}
|
||||
|
||||
/// One epilogue variant against the plain product plus the bias and the starting values.
|
||||
struct Epilogue<'a> {
|
||||
plain: &'a [f32],
|
||||
bias: &'a [f32],
|
||||
start: &'a [f32],
|
||||
dims: (usize, usize),
|
||||
flags: (bool, bool), // bias, accumulate
|
||||
}
|
||||
|
||||
impl Epilogue<'_> {
|
||||
fn check(&self, got: &[f32]) {
|
||||
let ((m, n), (use_bias, accumulate)) = (self.dims, self.flags);
|
||||
for i in 0..m {
|
||||
for j in 0..n {
|
||||
let mut want = self.plain[i * n + j];
|
||||
if use_bias {
|
||||
want += self.bias[j];
|
||||
}
|
||||
if accumulate {
|
||||
want += self.start[i * n + j];
|
||||
}
|
||||
let g = got[i * n + j];
|
||||
// the same f32 adds in the same order inside the kernel: equal up to the one rounding
|
||||
assert!(
|
||||
(g - want).abs() <= 1e-5 * (1.0 + want.abs()),
|
||||
"bias={use_bias} acc={accumulate} ({i},{j}): {g} vs {want}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU product with the epilogue flags applied on top of `start`.
|
||||
fn run_epilogue(
|
||||
gpu: &Gpu,
|
||||
(wm, am): (&leleka_igpu::GpuMatrix, &leleka_igpu::GpuActivations),
|
||||
(bias, start): (&[f32], &[f32]),
|
||||
(use_bias, accumulate): (bool, bool),
|
||||
) -> Vec<f32> {
|
||||
let bias_buf = gpu.buf_f32(bias);
|
||||
let out = gpu.buf_f32(start);
|
||||
let mut rec = gpu.recorder();
|
||||
rec.matmul(wm, am, &out, use_bias.then_some(&bias_buf), accumulate)
|
||||
.unwrap();
|
||||
rec.submit().unwrap();
|
||||
gpu.read_f32(&out).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_and_accumulation_are_added_in_the_epilogue() {
|
||||
let Some(gpu) = gpu() else { return };
|
||||
@@ -193,30 +254,15 @@ fn bias_and_accumulation_are_added_in_the_epilogue() {
|
||||
let plain = gpu.matmul(&wm, &am).unwrap();
|
||||
let bias: Vec<f32> = (0..n).map(|_| rng.unit()).collect();
|
||||
let start: Vec<f32> = (0..m * n).map(|_| rng.unit()).collect();
|
||||
let bias_buf = gpu.buf_f32(&bias);
|
||||
for (use_bias, accumulate) in [(true, false), (false, true), (true, true)] {
|
||||
let out = gpu.buf_f32(&start);
|
||||
let mut rec = gpu.recorder();
|
||||
rec.matmul(&wm, &am, &out, use_bias.then_some(&bias_buf), accumulate)
|
||||
.unwrap();
|
||||
rec.submit().unwrap();
|
||||
let got = gpu.read_f32(&out).unwrap();
|
||||
for i in 0..m {
|
||||
for j in 0..n {
|
||||
let mut want = plain[i * n + j];
|
||||
if use_bias {
|
||||
want += bias[j];
|
||||
}
|
||||
if accumulate {
|
||||
want += start[i * n + j];
|
||||
}
|
||||
let g = got[i * n + j];
|
||||
// the same f32 adds in the same order inside the kernel: equal up to the one rounding
|
||||
assert!(
|
||||
(g - want).abs() <= 1e-5 * (1.0 + want.abs()),
|
||||
"bias={use_bias} acc={accumulate} ({i},{j}): {g} vs {want}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for flags in [(true, false), (false, true), (true, true)] {
|
||||
let got = run_epilogue(&gpu, (&wm, &am), (&bias, &start), flags);
|
||||
let epilogue = Epilogue {
|
||||
plain: &plain,
|
||||
bias: &bias,
|
||||
start: &start,
|
||||
dims: (m, n),
|
||||
flags,
|
||||
};
|
||||
epilogue.check(&got);
|
||||
}
|
||||
}
|
||||
|
||||
+116
-71
@@ -6,7 +6,7 @@
|
||||
use leleka_cpu_kernels::Dispatch;
|
||||
use leleka_cpu_sys::simd::{e8m0_half, f16_to_f32};
|
||||
use leleka_gptoss::ops;
|
||||
use leleka_igpu::{Gpu, SwigluParams, WeightKind};
|
||||
use leleka_igpu::{Gpu, MoePlan, SwigluParams, WeightKind};
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
@@ -128,15 +128,19 @@ fn router_picks_the_cpu_experts_and_weights() {
|
||||
for (l, b) in logits.iter_mut().zip(&bias) {
|
||||
*l += b;
|
||||
}
|
||||
let want = ops::route_top_k(&logits, 4);
|
||||
for (slot, (ex, weight)) in want.iter().enumerate() {
|
||||
assert_eq!(got_ids[t * 4 + slot] as usize, *ex, "token {t} slot {slot}");
|
||||
assert!(
|
||||
(got_w[t * 4 + slot] - weight).abs() <= 1e-5,
|
||||
"token {t} slot {slot}: {} vs {weight}",
|
||||
got_w[t * 4 + slot]
|
||||
);
|
||||
}
|
||||
check_route(t, &ops::route_top_k(&logits, 4), &got_ids, &got_w);
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU route of token `t` (expert, weight per slot) against the GPU's ids and weights.
|
||||
fn check_route(t: usize, want: &[(usize, f32)], got_ids: &[u32], got_w: &[f32]) {
|
||||
for (slot, (ex, weight)) in want.iter().enumerate() {
|
||||
assert_eq!(got_ids[t * 4 + slot] as usize, *ex, "token {t} slot {slot}");
|
||||
assert!(
|
||||
(got_w[t * 4 + slot] - weight).abs() <= 1e-5,
|
||||
"token {t} slot {slot}: {} vs {weight}",
|
||||
got_w[t * 4 + slot]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,84 +167,95 @@ fn reference(d: &Dispatch, w: &[u8], a: &[u8], blocks: usize) -> (f64, f64) {
|
||||
(exact, magnitude)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_expert_products_and_combine_match_the_cpu() {
|
||||
let Some(gpu) = gpu() else { return };
|
||||
let d = Dispatch::best();
|
||||
let mut rng = Rng(14);
|
||||
let (experts, n, blocks, m, used) = (6usize, 40usize, 5usize, 70usize, 4usize);
|
||||
let e = 64usize; // width of the expert outputs for the combine
|
||||
let w = mxfp4_rows(&mut rng, experts * n, blocks);
|
||||
let wm = gpu
|
||||
.upload_matrix(WeightKind::Mxfp4, experts * n, blocks * 32, &w)
|
||||
.unwrap();
|
||||
let bias: Vec<f32> = (0..experts * n).map(|_| rng.unit()).collect();
|
||||
let bb = gpu.buf_f32(&bias);
|
||||
let x: Vec<f32> = (0..m * blocks * 32).map(|_| rng.unit() * 4.0).collect();
|
||||
let mut a = vec![0u8; m * blocks * 34];
|
||||
const EXPERTS: usize = 6;
|
||||
const N: usize = 40;
|
||||
const BLOCKS: usize = 5;
|
||||
const M: usize = 70;
|
||||
const USED: usize = 4;
|
||||
/// Width of the expert outputs for the combine.
|
||||
const E: usize = 64;
|
||||
|
||||
/// Random expert weights, biases, quantized activations and the experts each token picks.
|
||||
struct MoeInputs {
|
||||
w: Vec<u8>,
|
||||
bias: Vec<f32>,
|
||||
a: Vec<u8>,
|
||||
chosen: Vec<u32>,
|
||||
}
|
||||
|
||||
fn moe_inputs(d: &Dispatch, rng: &mut Rng) -> MoeInputs {
|
||||
let w = mxfp4_rows(rng, EXPERTS * N, BLOCKS);
|
||||
let bias: Vec<f32> = (0..EXPERTS * N).map(|_| rng.unit()).collect();
|
||||
let x: Vec<f32> = (0..M * BLOCKS * 32).map(|_| rng.unit() * 4.0).collect();
|
||||
let mut a = vec![0u8; M * BLOCKS * 34];
|
||||
d.quantize_q8_0(&x, &mut a).unwrap();
|
||||
let am = gpu.upload_activations(m, blocks * 32, &a).unwrap();
|
||||
// each token picks `used` distinct experts
|
||||
// each token picks `USED` distinct experts
|
||||
let mut chosen = Vec::new();
|
||||
for _ in 0..m {
|
||||
for _ in 0..M {
|
||||
let mut picks = Vec::new();
|
||||
while picks.len() < used {
|
||||
let ex = (rng.next() % experts as u64) as u32;
|
||||
while picks.len() < USED {
|
||||
let ex = (rng.next() % EXPERTS as u64) as u32;
|
||||
if !picks.contains(&ex) {
|
||||
picks.push(ex);
|
||||
}
|
||||
}
|
||||
chosen.extend(picks);
|
||||
}
|
||||
let plan = gpu.plan_moe(&chosen, used, experts).unwrap();
|
||||
assert_eq!(plan.entries(), m * used);
|
||||
let out = gpu.zeros(plan.entries() * n);
|
||||
MoeInputs { w, bias, a, chosen }
|
||||
}
|
||||
|
||||
/// One output column of one entry against the exact reference.
|
||||
fn check_column(
|
||||
d: &Dispatch,
|
||||
inp: &MoeInputs,
|
||||
got: &[f32],
|
||||
(entry, ex, t, c): (usize, usize, usize, usize),
|
||||
) {
|
||||
let wrow = &inp.w[(ex * N + c) * BLOCKS * 17..(ex * N + c + 1) * BLOCKS * 17];
|
||||
let arow = &inp.a[t * BLOCKS * 34..(t + 1) * BLOCKS * 34];
|
||||
let (exact, magnitude) = reference(d, wrow, arow, BLOCKS);
|
||||
let want = exact + f64::from(inp.bias[ex * N + c]);
|
||||
let tolerance = magnitude * (BLOCKS as f64 + 8.0) * 2f64.powi(-23) + 1e-6;
|
||||
let g = f64::from(got[entry * N + c]);
|
||||
assert!(
|
||||
(g - want).abs() <= tolerance,
|
||||
"expert {ex} token {t} column {c}: gpu {g} vs {want} (tolerance {tolerance})"
|
||||
);
|
||||
}
|
||||
|
||||
/// The grouped expert products against the exact references, in entry order.
|
||||
fn check_expert_products(gpu: &Gpu, d: &Dispatch, inp: &MoeInputs, plan: &MoePlan) {
|
||||
let wm = gpu
|
||||
.upload_matrix(WeightKind::Mxfp4, EXPERTS * N, BLOCKS * 32, &inp.w)
|
||||
.unwrap();
|
||||
let bb = gpu.buf_f32(&inp.bias);
|
||||
let am = gpu.upload_activations(M, BLOCKS * 32, &inp.a).unwrap();
|
||||
let out = gpu.zeros(plan.entries() * N);
|
||||
let mut rec = gpu.recorder();
|
||||
rec.moe_matmul(&wm, &am, &plan, true, Some(&bb), &out)
|
||||
rec.moe_matmul(&wm, &am, plan, true, Some(&bb), &out)
|
||||
.unwrap();
|
||||
rec.submit().unwrap();
|
||||
let got = gpu.read_f32(&out).unwrap();
|
||||
// entry order: by expert, tokens ascending, slots ascending
|
||||
let mut entry = 0usize;
|
||||
for ex in 0..experts {
|
||||
for (i, pick) in chosen.iter().enumerate() {
|
||||
for ex in 0..EXPERTS {
|
||||
for (i, pick) in inp.chosen.iter().enumerate() {
|
||||
if *pick as usize != ex {
|
||||
continue;
|
||||
}
|
||||
let t = i / used;
|
||||
for c in 0..n {
|
||||
let wrow = &w[(ex * n + c) * blocks * 17..(ex * n + c + 1) * blocks * 17];
|
||||
let arow = &a[t * blocks * 34..(t + 1) * blocks * 34];
|
||||
let (exact, magnitude) = reference(&d, wrow, arow, blocks);
|
||||
let want = exact + f64::from(bias[ex * n + c]);
|
||||
let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23) + 1e-6;
|
||||
let g = f64::from(got[entry * n + c]);
|
||||
assert!(
|
||||
(g - want).abs() <= tolerance,
|
||||
"expert {ex} token {t} column {c}: gpu {g} vs {want} (tolerance {tolerance})"
|
||||
);
|
||||
for c in 0..N {
|
||||
check_column(d, inp, &got, (entry, ex, i / USED, c));
|
||||
}
|
||||
entry += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(entry, plan.entries());
|
||||
}
|
||||
|
||||
// the combine: down outputs are random, weights random; result = x + sum over slots in order
|
||||
let down: Vec<f32> = (0..plan.entries() * e).map(|_| rng.unit()).collect();
|
||||
let weights: Vec<f32> = (0..m * used).map(|_| rng.unit().abs()).collect();
|
||||
let resid: Vec<f32> = (0..m * e).map(|_| rng.unit()).collect();
|
||||
let (db, wb, xb) = (
|
||||
gpu.buf_f32(&down),
|
||||
gpu.buf_f32(&weights),
|
||||
gpu.buf_f32(&resid),
|
||||
);
|
||||
let mut rec = gpu.recorder();
|
||||
rec.moe_combine(&db, &plan, &wb, &xb, e).unwrap();
|
||||
rec.submit().unwrap();
|
||||
let got = gpu.read_f32(&xb).unwrap();
|
||||
// entry index of each (token, slot): count earlier picks of the same expert
|
||||
let mut next = vec![0usize; experts];
|
||||
let mut start = vec![0usize; experts];
|
||||
/// Entry index of each (token, slot): the first entry of its expert plus the earlier picks of that expert.
|
||||
fn entry_indices(chosen: &[u32]) -> Vec<usize> {
|
||||
let mut next = [0usize; EXPERTS];
|
||||
let mut start = [0usize; EXPERTS];
|
||||
let mut total = 0;
|
||||
for (ex, first) in start.iter_mut().enumerate() {
|
||||
*first = total;
|
||||
@@ -251,22 +266,52 @@ fn grouped_expert_products_and_combine_match_the_cpu() {
|
||||
entry_of[i] = start[*pick as usize] + next[*pick as usize];
|
||||
next[*pick as usize] += 1;
|
||||
}
|
||||
for t in 0..m {
|
||||
for r in 0..e {
|
||||
entry_of
|
||||
}
|
||||
|
||||
/// The combine: down outputs are random, weights random; result = x + sum over slots in order.
|
||||
fn check_combine(gpu: &Gpu, rng: &mut Rng, inp: &MoeInputs, plan: &MoePlan) {
|
||||
let down: Vec<f32> = (0..plan.entries() * E).map(|_| rng.unit()).collect();
|
||||
let weights: Vec<f32> = (0..M * USED).map(|_| rng.unit().abs()).collect();
|
||||
let resid: Vec<f32> = (0..M * E).map(|_| rng.unit()).collect();
|
||||
let (db, wb, xb) = (
|
||||
gpu.buf_f32(&down),
|
||||
gpu.buf_f32(&weights),
|
||||
gpu.buf_f32(&resid),
|
||||
);
|
||||
let mut rec = gpu.recorder();
|
||||
rec.moe_combine(&db, plan, &wb, &xb, E).unwrap();
|
||||
rec.submit().unwrap();
|
||||
let got = gpu.read_f32(&xb).unwrap();
|
||||
let entry_of = entry_indices(&inp.chosen);
|
||||
for t in 0..M {
|
||||
for r in 0..E {
|
||||
let mut acc = 0.0f32;
|
||||
for s in 0..used {
|
||||
acc += weights[t * used + s] * down[entry_of[t * used + s] * e + r];
|
||||
for s in 0..USED {
|
||||
acc += weights[t * USED + s] * down[entry_of[t * USED + s] * E + r];
|
||||
}
|
||||
let want = resid[t * e + r] + acc;
|
||||
let want = resid[t * E + r] + acc;
|
||||
assert!(
|
||||
(got[t * e + r] - want).abs() <= 1e-5 * (1.0 + want.abs()),
|
||||
(got[t * E + r] - want).abs() <= 1e-5 * (1.0 + want.abs()),
|
||||
"token {t} element {r}: {} vs {want}",
|
||||
got[t * e + r]
|
||||
got[t * E + r]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_expert_products_and_combine_match_the_cpu() {
|
||||
let Some(gpu) = gpu() else { return };
|
||||
let d = Dispatch::best();
|
||||
let mut rng = Rng(14);
|
||||
let inp = moe_inputs(&d, &mut rng);
|
||||
let plan = gpu.plan_moe(&inp.chosen, USED, EXPERTS).unwrap();
|
||||
assert_eq!(plan.entries(), M * USED);
|
||||
check_expert_products(&gpu, &d, &inp, &plan);
|
||||
check_combine(&gpu, &mut rng, &inp, &plan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_plans_are_refused() {
|
||||
let Some(gpu) = gpu() else { return };
|
||||
|
||||
+44
-26
@@ -26,13 +26,15 @@ impl Rng {
|
||||
}
|
||||
}
|
||||
|
||||
fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) {
|
||||
let d = Dispatch::best();
|
||||
let mut rng = Rng(seed);
|
||||
let x: Vec<f32> = (0..rows * e).map(|_| rng.unit()).collect();
|
||||
let w: Vec<f32> = (0..e).map(|_| 0.5 + rng.unit().abs() * 0.25).collect();
|
||||
let eps = 1e-5f32;
|
||||
let (xb, wb) = (gpu.buf_f32(&x), gpu.buf_f32(&w));
|
||||
/// What the GPU produced for the rows: normalised values, packed quants and block scales.
|
||||
struct GpuNorm {
|
||||
h: Vec<f32>,
|
||||
words: Vec<u32>,
|
||||
scales: Vec<f32>,
|
||||
}
|
||||
|
||||
fn run_gpu_norm(gpu: &Gpu, x: &[f32], w: &[f32], (rows, e): (usize, usize), eps: f32) -> GpuNorm {
|
||||
let (xb, wb) = (gpu.buf_f32(x), gpu.buf_f32(w));
|
||||
let normalized = gpu.zeros(rows * e);
|
||||
let act = gpu.new_activations(rows, e).unwrap();
|
||||
let mut rec = gpu.recorder();
|
||||
@@ -41,37 +43,53 @@ fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) {
|
||||
rec.submit().unwrap();
|
||||
let h = gpu.read_f32(&normalized).unwrap();
|
||||
let (words, scales) = gpu.read_activations(&act).unwrap();
|
||||
GpuNorm { h, words, scales }
|
||||
}
|
||||
|
||||
/// The quantized blocks of row `r` against the CPU quantizer; returns the number of one-step differences.
|
||||
fn check_row_quant(got: &GpuNorm, r: usize, want: &[f32]) -> usize {
|
||||
let e = want.len();
|
||||
let blocks = e / 32;
|
||||
let mut q = vec![0u8; blocks * 34];
|
||||
Dispatch::best().quantize_q8_0(want, &mut q).unwrap();
|
||||
let mut flips = 0usize;
|
||||
for b in 0..blocks {
|
||||
let blk = &q[b * 34..(b + 1) * 34];
|
||||
let cpu_scale = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]]));
|
||||
let gpu_scale = got.scales[r * blocks + b];
|
||||
assert!(
|
||||
gpu_scale == cpu_scale,
|
||||
"row {r} block {b}: scale {gpu_scale} vs {cpu_scale}"
|
||||
);
|
||||
for i in 0..32 {
|
||||
let g = got.words[(r * blocks + b) * 8 + i / 4].to_le_bytes()[i % 4] as i8;
|
||||
let c = blk[2 + i] as i8;
|
||||
let diff = (i32::from(g) - i32::from(c)).abs();
|
||||
assert!(diff <= 1, "row {r} block {b} element {i}: {g} vs {c}");
|
||||
flips += usize::from(diff != 0);
|
||||
}
|
||||
}
|
||||
flips
|
||||
}
|
||||
|
||||
fn check(gpu: &Gpu, rows: usize, e: usize, seed: u64) {
|
||||
let mut rng = Rng(seed);
|
||||
let x: Vec<f32> = (0..rows * e).map(|_| rng.unit()).collect();
|
||||
let w: Vec<f32> = (0..e).map(|_| 0.5 + rng.unit().abs() * 0.25).collect();
|
||||
let eps = 1e-5f32;
|
||||
let got = run_gpu_norm(gpu, &x, &w, (rows, e), eps);
|
||||
let mut flips = 0usize;
|
||||
for r in 0..rows {
|
||||
let mut want = vec![0f32; e];
|
||||
rms_norm(&x[r * e..(r + 1) * e], &w, eps, &mut want);
|
||||
for (i, wv) in want.iter().enumerate() {
|
||||
let g = h[r * e + i];
|
||||
let g = got.h[r * e + i];
|
||||
assert!(
|
||||
(g - wv).abs() <= 1e-5 * (1.0 + wv.abs()),
|
||||
"row {r} element {i}: gpu {g} vs cpu {wv}"
|
||||
);
|
||||
}
|
||||
let mut q = vec![0u8; blocks * 34];
|
||||
d.quantize_q8_0(&want, &mut q).unwrap();
|
||||
for b in 0..blocks {
|
||||
let blk = &q[b * 34..(b + 1) * 34];
|
||||
let cpu_scale = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]]));
|
||||
let gpu_scale = scales[r * blocks + b];
|
||||
assert!(
|
||||
gpu_scale == cpu_scale,
|
||||
"row {r} block {b}: scale {gpu_scale} vs {cpu_scale}"
|
||||
);
|
||||
for i in 0..32 {
|
||||
let g = words[(r * blocks + b) * 8 + i / 4].to_le_bytes()[i % 4] as i8;
|
||||
let c = blk[2 + i] as i8;
|
||||
let diff = (i32::from(g) - i32::from(c)).abs();
|
||||
assert!(diff <= 1, "row {r} block {b} element {i}: {g} vs {c}");
|
||||
flips += usize::from(diff != 0);
|
||||
}
|
||||
}
|
||||
flips += check_row_quant(&got, r, &want);
|
||||
}
|
||||
let total = rows * e;
|
||||
assert!(
|
||||
|
||||
@@ -11,11 +11,41 @@ use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
use std::path::Path;
|
||||
|
||||
fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, label: &str) {
|
||||
let blocks = 90;
|
||||
let block_bytes = if kind == WeightKind::Q8_0 { 34 } else { 17 };
|
||||
assert_eq!(weights.len(), rows * blocks * block_bytes, "{label}");
|
||||
let d = Dispatch::best();
|
||||
/// The exact value (and the sum of the term magnitudes) of one output: the integer block sums combined with
|
||||
/// the block scales in f64.
|
||||
fn exact_output(
|
||||
d: &Dispatch,
|
||||
kind: WeightKind,
|
||||
arow: &[u8],
|
||||
wrow: &[u8],
|
||||
sums: &mut [i32],
|
||||
) -> (f64, f64) {
|
||||
match kind {
|
||||
WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, sums).unwrap(),
|
||||
WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, sums).unwrap(),
|
||||
}
|
||||
let (mut exact, mut magnitude) = (0f64, 0f64);
|
||||
for b in 0..sums.len() {
|
||||
let sa = f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
arow[b * 34],
|
||||
arow[b * 34 + 1],
|
||||
])));
|
||||
let sw = match kind {
|
||||
WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
wrow[b * 34],
|
||||
wrow[b * 34 + 1],
|
||||
]))),
|
||||
WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])),
|
||||
};
|
||||
let term = f64::from(sums[b]) * sa * sw;
|
||||
exact += term;
|
||||
magnitude += term.abs();
|
||||
}
|
||||
(exact, magnitude)
|
||||
}
|
||||
|
||||
/// `m` rows of pseudo-random activations of `blocks` blocks, quantized to Q8_0.
|
||||
fn random_activations(d: &Dispatch, m: usize, blocks: usize) -> Vec<u8> {
|
||||
let mut state = 0x1234_5678_9ABC_DEF1u64;
|
||||
let x: Vec<f32> = (0..m * blocks * 32)
|
||||
.map(|_| {
|
||||
@@ -27,6 +57,15 @@ fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, l
|
||||
.collect();
|
||||
let mut a = vec![0u8; m * blocks * 34];
|
||||
d.quantize_q8_0(&x, &mut a).unwrap();
|
||||
a
|
||||
}
|
||||
|
||||
fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, label: &str) {
|
||||
let blocks = 90;
|
||||
let block_bytes = if kind == WeightKind::Q8_0 { 34 } else { 17 };
|
||||
assert_eq!(weights.len(), rows * blocks * block_bytes, "{label}");
|
||||
let d = Dispatch::best();
|
||||
let a = random_activations(&d, m, blocks);
|
||||
let wm = gpu.upload_matrix(kind, rows, blocks * 32, weights).unwrap();
|
||||
let am = gpu.upload_activations(m, blocks * 32, &a).unwrap();
|
||||
let got = gpu.matmul(&wm, &am).unwrap();
|
||||
@@ -37,27 +76,7 @@ fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, l
|
||||
let arow = &a[i * blocks * 34..(i + 1) * blocks * 34];
|
||||
for j in (0..rows).step_by(7).chain([rows - 1]) {
|
||||
let wrow = &weights[j * blocks * block_bytes..(j + 1) * blocks * block_bytes];
|
||||
match kind {
|
||||
WeightKind::Q8_0 => d.q8_0_q8_0_block_sums(wrow, arow, &mut sums).unwrap(),
|
||||
WeightKind::Mxfp4 => d.mxfp4_q8_0_block_sums(wrow, arow, &mut sums).unwrap(),
|
||||
}
|
||||
let (mut exact, mut magnitude) = (0f64, 0f64);
|
||||
for b in 0..blocks {
|
||||
let sa = f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
arow[b * 34],
|
||||
arow[b * 34 + 1],
|
||||
])));
|
||||
let sw = match kind {
|
||||
WeightKind::Q8_0 => f64::from(f16_to_f32(u16::from_le_bytes([
|
||||
wrow[b * 34],
|
||||
wrow[b * 34 + 1],
|
||||
]))),
|
||||
WeightKind::Mxfp4 => f64::from(e8m0_half(wrow[b * 17])),
|
||||
};
|
||||
let term = f64::from(sums[b]) * sa * sw;
|
||||
exact += term;
|
||||
magnitude += term.abs();
|
||||
}
|
||||
let (exact, magnitude) = exact_output(&d, kind, arow, wrow, &mut sums);
|
||||
let tolerance = magnitude * (blocks as f64 + 8.0) * 2f64.powi(-23);
|
||||
let error = (f64::from(got[i * rows + j]) - exact).abs();
|
||||
worst = worst.max(error / tolerance.max(1e-30));
|
||||
@@ -68,10 +87,20 @@ fn compare(gpu: &Gpu, kind: WeightKind, weights: &[u8], rows: usize, m: usize, l
|
||||
);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"{label}: {m} x {rows} x 2880 ok, worst error {:.2} of the tolerance",
|
||||
worst
|
||||
);
|
||||
eprintln!("{label}: {m} x {rows} x 2880 ok, worst error {worst:.2} of the tolerance");
|
||||
}
|
||||
|
||||
fn open_model(path: &Path) -> (Gguf, Mapping) {
|
||||
let size = std::fs::metadata(path).unwrap().len();
|
||||
let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap();
|
||||
(gguf, Mapping::open(path).unwrap())
|
||||
}
|
||||
|
||||
/// One expert (2880 rows of 2880) of a stacked MXFP4 tensor.
|
||||
fn compare_expert(gpu: &Gpu, all: &[u8], index: usize, m: usize, label: &str) {
|
||||
let expert = 2880 * 90 * 17;
|
||||
let weights = &all[index * expert..(index + 1) * expert];
|
||||
compare(gpu, WeightKind::Mxfp4, weights, 2880, m, label);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -84,10 +113,7 @@ fn real_attention_and_expert_weights_match_the_cpu_kernels() {
|
||||
eprintln!("skipped: no GPU");
|
||||
return;
|
||||
};
|
||||
let path = Path::new(&path);
|
||||
let size = std::fs::metadata(path).unwrap().len();
|
||||
let gguf = Gguf::read(BufReader::new(File::open(path).unwrap()), size).unwrap();
|
||||
let map = Mapping::open(path).unwrap();
|
||||
let (gguf, map) = open_model(Path::new(&path));
|
||||
let bytes = map.as_bytes();
|
||||
let tensor = |name: &str| {
|
||||
let t = gguf.tensor(name).unwrap_or_else(|| panic!("tensor {name}"));
|
||||
@@ -101,23 +127,8 @@ fn real_attention_and_expert_weights_match_the_cpu_kernels() {
|
||||
// one expert's gate and up projections of layer 5 (MXFP4): 2880 rows of 2880 each
|
||||
let (gate, dims) = tensor("blk.5.ffn_gate_exps.weight");
|
||||
assert_eq!(dims, vec![2880, 2880, 32]);
|
||||
let expert = 2880 * 90 * 17;
|
||||
compare(
|
||||
&gpu,
|
||||
WeightKind::Mxfp4,
|
||||
&gate[11 * expert..12 * expert],
|
||||
2880,
|
||||
29,
|
||||
"blk.5.ffn_gate_exps[11] (MXFP4)",
|
||||
);
|
||||
compare_expert(&gpu, gate, 11, 29, "blk.5.ffn_gate_exps[11] (MXFP4)");
|
||||
// the last layer's down projection, last expert
|
||||
let (down, _) = tensor("blk.23.ffn_down_exps.weight");
|
||||
compare(
|
||||
&gpu,
|
||||
WeightKind::Mxfp4,
|
||||
&down[31 * expert..32 * expert],
|
||||
2880,
|
||||
8,
|
||||
"blk.23.ffn_down_exps[31] (MXFP4)",
|
||||
);
|
||||
compare_expert(&gpu, down, 31, 8, "blk.23.ffn_down_exps[31] (MXFP4)");
|
||||
}
|
||||
|
||||
@@ -13,6 +13,26 @@ const PROMPT: [u32; 5] = [976, 9029, 328, 10128, 382];
|
||||
/// tiny numeric differences flip).
|
||||
const FIRST_TOKEN: u32 = 12650;
|
||||
|
||||
/// The command line that serves `model` with every prompt of at least one token on the NPU.
|
||||
fn worker_args<'a>(model: &'a str, root: &'a str, device: &'a str) -> [&'a str; 14] {
|
||||
[
|
||||
"--serve",
|
||||
"--model",
|
||||
model,
|
||||
"--threads",
|
||||
"4",
|
||||
"--ctx",
|
||||
"512",
|
||||
"--no-warm",
|
||||
"--openvino-root",
|
||||
root,
|
||||
"--npu-device",
|
||||
device,
|
||||
"--npu-min-tokens",
|
||||
"1",
|
||||
]
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
@@ -24,22 +44,7 @@ impl Worker {
|
||||
let root = std::env::var("LELEKA_OPENVINO_ROOT").expect("LELEKA_OPENVINO_ROOT");
|
||||
let device = std::env::var("LELEKA_OPENVINO_DEVICE").unwrap_or_else(|_| "NPU".into());
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_leleka-npu-worker"))
|
||||
.args([
|
||||
"--serve",
|
||||
"--model",
|
||||
model,
|
||||
"--threads",
|
||||
"4",
|
||||
"--ctx",
|
||||
"512",
|
||||
"--no-warm",
|
||||
"--openvino-root",
|
||||
&root,
|
||||
"--npu-device",
|
||||
&device,
|
||||
"--npu-min-tokens",
|
||||
"1",
|
||||
])
|
||||
.args(worker_args(model, &root, &device))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
@@ -103,8 +108,17 @@ fn the_npu_worker_serves_prompts_and_continues_from_a_cached_prefix() {
|
||||
return;
|
||||
};
|
||||
let mut worker = Worker::start(&model);
|
||||
let tokens = first_prompt_is_served(&mut worker);
|
||||
cached_prefix_is_reused(&mut worker, &tokens);
|
||||
|
||||
// the whole prompt is prefilled on the GPU (--gpu-min-tokens 1)
|
||||
// a different prompt shares one token and still works after the reuse
|
||||
let (tokens, _, reused) = worker.generate(3, &[976, 9029]);
|
||||
assert_eq!(tokens.len(), 3);
|
||||
assert_eq!(reused, 1);
|
||||
}
|
||||
|
||||
/// The whole prompt is prefilled on the NPU; returns the generated tokens.
|
||||
fn first_prompt_is_served(worker: &mut Worker) -> Vec<u32> {
|
||||
let (tokens, done, reused) = worker.generate(16, &PROMPT);
|
||||
assert_eq!(tokens.len(), 16);
|
||||
assert_eq!(tokens[0], FIRST_TOKEN);
|
||||
@@ -112,18 +126,16 @@ fn the_npu_worker_serves_prompts_and_continues_from_a_cached_prefix() {
|
||||
let fields: Vec<&str> = done.split_whitespace().collect();
|
||||
assert_eq!(&fields[1..3], ["16", "5"], "{done}");
|
||||
assert_eq!(fields[5], "length");
|
||||
tokens
|
||||
}
|
||||
|
||||
// the prompt plus the first four generated tokens: the cached prefix is reused and the NPU path computes
|
||||
// only the last token on top of keys and values it did not produce. The numbers differ slightly from
|
||||
// the CPU's, so near-tie tokens may differ; the count and the reuse are what is checked.
|
||||
/// The prompt plus the first four generated tokens: the cached prefix is reused and the NPU path computes
|
||||
/// only the last token on top of keys and values it did not produce. The numbers differ slightly from
|
||||
/// the CPU's, so near-tie tokens may differ; the count and the reuse are what is checked.
|
||||
fn cached_prefix_is_reused(worker: &mut Worker, tokens: &[u32]) {
|
||||
let mut longer = PROMPT.to_vec();
|
||||
longer.extend_from_slice(&tokens[..4]);
|
||||
let (continued, done, reused) = worker.generate(12, &longer);
|
||||
assert_eq!(reused, longer.len() - 1, "{done}");
|
||||
assert_eq!(continued.len(), 12);
|
||||
|
||||
// a different prompt shares one token and still works after the reuse
|
||||
let (tokens, _, reused) = worker.generate(3, &[976, 9029]);
|
||||
assert_eq!(tokens.len(), 3);
|
||||
assert_eq!(reused, 1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user