use super::{ArgmaxArgs, SampArgs};
use crate::metal::{Enc, Gpu};
use objc2_metal::{
MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCreateSystemDefaultDevice,
};
const WIDTH: usize = 2049;
const PARTS: usize = WIDTH.div_ceil(1024);
fn sample_rows(gpu: &Gpu, rows: &[[f32; WIDTH]; 2], temps: [f32; 2], bans: [u32; 2]) -> [u32; 2] {
let score_words = rows.len() * WIDTH;
let arena = gpu.buffer((score_words + rows.len() * 2 * PARTS) * size_of::<f32>());
let tokens = gpu.buffer(rows.len() * size_of::<u32>());
unsafe {
std::ptr::copy_nonoverlapping(
rows.as_ptr().cast::<f32>(),
arena.contents().as_ptr().cast(),
score_words,
);
}
let cb = gpu.cmd();
let e = Enc::new(&cb);
e.buf(&arena, 0, 2);
e.buf(&tokens, 0, 6);
e.pso(&gpu.pso("k_gumbel"));
for i in 0..rows.len() {
let args = SampArgs {
logits_off: (i * WIDTH) as u32,
n: WIDTH as u32,
seed_lo: 19,
seed_hi: 0,
pos: 3,
ban_tok: bans[i],
temp: temps[i],
softcap: 30.0,
};
e.bytes(&args, 5);
e.dispatch((WIDTH.div_ceil(256), 1, 1), 256);
}
e.barrier();
for (kernel, groups, threads) in [("k_argmax1", PARTS, 1024), ("k_argmax2", 1, 32)] {
e.pso(&gpu.pso(kernel));
for i in 0..rows.len() {
let args = ArgmaxArgs {
logits_off: (i * WIDTH) as u32,
n: WIDTH as u32,
part_off: (score_words + i * 2 * PARTS) as u32,
nparts: PARTS as u32,
out_index: i as u32,
checked: 1,
pad: [0; 2],
};
e.bytes(&args, 5);
e.dispatch((groups, 1, 1), threads);
}
e.barrier();
}
e.end();
cb.commit();
cb.waitUntilCompleted();
assert_eq!(
cb.status(),
MTLCommandBufferStatus::Completed,
"{:?}",
cb.error()
);
unsafe { *tokens.contents().as_ptr().cast::<[u32; 2]>() }
}
#[test]
fn metal_sampling_validates_each_row_and_preserves_greedy_order() {
if MTLCreateSystemDefaultDevice().is_none() {
eprintln!("Metal sampling regression skipped: no Metal device");
return;
}
let all = include_str!("../kernels.metal");
let start = all.find("// argmax over logits").unwrap();
let end = all[start..].find("// Adaptive LoopCD-Logits").unwrap();
let src = format!(
"#include <metal_stdlib>\nusing namespace metal;\n{}",
&all[start..start + end]
);
let gpu = Gpu::new(&src, &["k_gumbel", "k_argmax1", "k_argmax2"]);
let mut rows = [[-20.0; WIDTH]; 2];
let above_twenty = f32::from_bits(20.0_f32.to_bits() + 1);
rows[0][1] = 21.0; rows[0][2] = 20.0;
rows[0][1025] = above_twenty;
rows[0][2048] = above_twenty; rows[1][12] = 20.0;
for temp in [0.0, 1.25e-38, 1e-6] {
let tokens = sample_rows(&gpu, &rows, [temp, 0.5], [1, u32::MAX]);
assert_eq!(tokens, [1025, 12], "temperature {temp}");
}
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
rows[0][2048] = bad;
for (temp, ban) in [(0.0, 1), (0.5, 1), (1.25e-38, 2048), (0.5, 2048)] {
let tokens = sample_rows(&gpu, &rows, [temp, 0.5], [ban, u32::MAX]);
assert_eq!(
tokens,
[u32::MAX, 12],
"logit {bad}, banned {ban}, temperature {temp}"
);
}
}
rows[0].fill(f32::NAN);
let tokens = sample_rows(&gpu, &rows, [1.0, 0.5], [u32::MAX; 2]);
assert_eq!(tokens, [u32::MAX, 12], "all-NaN row");
let mut cpu_tie_row = [-15.0f32; WIDTH];
cpu_tie_row[513] = 420.0;
cpu_tie_row[1537] = 425.0; let mut finite_ctrl = [-15.0f32; WIDTH];
finite_ctrl[77] = 25.0;
for temp in [0.0f32, 1.0e-38, 1.25e-38, 1.0e-6] {
let mut cpu_sampler = crate::sampler::Sampler::new(temp, 0, 1.0, 30.0, 19);
let cpu_tok = cpu_sampler.sample_next(&cpu_tie_row).unwrap();
assert_eq!(cpu_tok, 1537, "CPU near-zero raw argmax at temp={temp}");
let gpu_pair = sample_rows(&gpu, &[cpu_tie_row, finite_ctrl], [temp, 0.7], [u32::MAX; 2]);
assert_eq!(gpu_pair[0], cpu_tok, "GPU batched near-zero mismatch at temp={temp}");
assert_eq!(gpu_pair[1], 77, "finite ordinary-temperature control disturbed at temp={temp}");
}
}
fn topk_rows(gpu: &Gpu, rows: &[Vec<f32>]) -> Vec<(bool, Vec<(f32, u32)>)> {
let width = rows.iter().map(Vec::len).max().unwrap();
let words = super::topk_row_words(width);
let tk = rows.len() * width;
let arena = gpu.buffer((tk + rows.len() * words) * 4);
let a = arena.contents().as_ptr().cast::<f32>();
for (r, row) in rows.iter().enumerate() {
unsafe { std::ptr::copy_nonoverlapping(row.as_ptr(), a.add(r * width), row.len()) };
}
let args = |r: usize| {
let n = rows[r].len();
let nchunks = n.div_ceil(super::TOPK_CHUNK);
let base = tk + r * words;
(
super::TopkCandArgs {
logits_off: (r * width) as u32,
n: n as u32,
nchunks: nchunks as u32,
part_off: base as u32,
out_off: (base + nchunks * super::TOPK_ROW) as u32,
pad: [0; 3],
},
nchunks,
)
};
let cb = gpu.cmd();
let e = Enc::new(&cb);
e.buf(&arena, 0, 2);
e.pso(&gpu.pso("k_topk_cand1"));
for r in 0..rows.len() {
let (args, nchunks) = args(r);
e.bytes(&args, 5);
e.dispatch((nchunks, 1, 1), 256);
}
e.barrier();
e.pso(&gpu.pso("k_topk_cand2"));
for r in 0..rows.len() {
let (args, nchunks) = args(r);
e.bytes(&args, 5);
e.dispatch((1, 1, 1), nchunks.div_ceil(32) * 32);
}
e.end();
cb.commit();
cb.waitUntilCompleted();
assert_eq!(cb.status(), MTLCommandBufferStatus::Completed, "{:?}", cb.error());
(0..rows.len())
.map(|r| {
let (args, _) = args(r);
let out = unsafe {
std::slice::from_raw_parts(a.cast::<u32>().add(args.out_off as usize), super::TOPK_ROW)
};
crate::sampler::decode_topk_row(out)
})
.collect()
}
#[test]
fn metal_topk_candidates_match_cpu_reference() {
if MTLCreateSystemDefaultDevice().is_none() {
eprintln!("Metal top-k regression skipped: no Metal device");
return;
}
let all = include_str!("../kernels.metal");
let start = all.find("// argmax over logits").unwrap();
let end = all[start..].find("// Adaptive LoopCD-Logits").unwrap();
let src = format!("#include <metal_stdlib>\nusing namespace metal;\n{}", &all[start..start + end]);
let gpu = Gpu::new(&src, &["k_topk_cand1", "k_topk_cand2"]);
let mut rng = 0x5EED_70B6_4000_0001u64;
let mut next = || {
rng = rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = rng;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
};
let mut rows: Vec<Vec<f32>> = Vec::new();
for (k, n) in [1usize, 2, 64, 65, 66, 255, 2047, 2048, 2049, 4097, 20000, 201_088].into_iter().enumerate() {
for style in 0..4 {
rows.push(
(0..n)
.map(|i| {
let u = next();
match style {
0 => [0.0, -0.0, 7.0, 7.0, -3.0, 0.0, -0.0, 1.0][(u % 8) as usize],
1 => ((u & 0xFFFFF) as f32) / 4096.0 - 128.0,
2 => if u % 1009 == 0 { 2.0 } else { 1.5 },
_ => f32::from_bits(((u as u32) & 0x807f_ffff) | (((k as u32 * 7 + i as u32) % 254 + 1) << 23)),
}
})
.collect(),
);
}
}
for (pos, bad) in [(0usize, f32::NAN), (2047, f32::INFINITY), (2048, f32::NEG_INFINITY), (201_087, f32::NAN)] {
let mut row: Vec<f32> = (0..201_088).map(|i| (i % 977) as f32 * 0.01).collect();
row[pos] = bad;
rows.push(row);
}
for n in [100usize, 4097] {
let row: Vec<f32> = (0..n)
.map(|i| match (next() % 6) as u32 {
0 => -0.0,
1 => 0.0,
2 => f32::from_bits(1 + (i as u32 % 0x7f_ffff)),
3 => -f32::from_bits(1 + (i as u32 % 0x7f_ffff)),
4 => f32::from_bits(1),
_ => -1e-30,
})
.collect();
rows.push(row);
}
let mut allbad = vec![f32::NAN; 3000];
allbad[5] = f32::INFINITY;
rows.push(allbad);
let got = topk_rows(&gpu, &rows);
for (r, (row, (gbad, gtop))) in rows.iter().zip(&got).enumerate() {
let (wbad, wtop) = crate::sampler::topk_reference(row);
assert_eq!(*gbad, wbad, "row {r} (n={}) nonfinite flag", row.len());
if wbad {
continue; }
let g: Vec<(u32, u32)> = gtop.iter().map(|c| (c.0.to_bits(), c.1)).collect();
let w: Vec<(u32, u32)> = wtop.iter().map(|c| (c.0.to_bits(), c.1)).collect();
assert_eq!(g, w, "row {r} (n={}) candidates", row.len());
for (t, (temp, top_k, top_p)) in [(0.0f32, 64usize, 0.95f32), (1.0, 64, 0.95), (0.7, 7, 0.5), (1.3, 1, 1.0)]
.into_iter()
.enumerate()
{
let ban = (t % 2 == 1).then(|| wtop[0].1);
let seed = 77 + (r * 4 + t) as u64;
let mut cpu = crate::sampler::Sampler::new(temp, top_k, top_p, 30.0, seed);
let mut gpu_s = crate::sampler::Sampler::new(temp, top_k, top_p, 30.0, seed);
let want = cpu.sample_next_with_ban_and_softcap(row, ban, 30.0);
let have = match gpu_s.sample_next_from_topk(gtop, row.len(), *gbad, ban, 30.0) {
Ok(None) => gpu_s.sample_next_with_ban_and_softcap(row, ban, 30.0),
other => other.map(|t| t.unwrap()),
};
assert_eq!(have, want, "row {r} (n={}) temp {temp} k {top_k} p {top_p} ban {ban:?}", row.len());
}
}
}