[HIP] Per-query flash determinism (default scalar) + DSpark ctx scatter kernel

Root cause of speculative losslessness divergence: the FA2 WMMA prefill flash
rescales o_acc/row_sum over a mixed-position query tile up to q_max_pos, so a
query's output depended on its batch neighbours by ~1 ulp (masked extra KV block
still rescales; __expf(0) is not exactly 1). That 1-ulp drift bf16-rounds into the
ShortConv hist and accumulates until a greedy near-tie flips (gate diverged at
token 46). The scalar f16 flash is per-query deterministic. Make WMMA flash OPT-IN
(VETTA_FLASH_WMMA=1); default to the verified scalar baseline. Guard alpha=1.0
exactly when nm==row_max. New flash_batch_determinism test: query0 M=2 vs M=1
maxdiff=0. Also add k_dspark_scatter_bf16 (f32 rows -> bf16 ring at pos%cap) for
DSpark context commit. hip suite 45/45.
This commit is contained in:
adm committed 2026-12-02 21:30:27 +01:00
1 parent ca12801b40
commit 6e854a9d73
2 files changed
+91 -3

No files matched your search

+52 -2
View File
@@ -69,6 +69,10 @@ mod ffi {
inp: *const c_float, a: *mut c_float, b: *mut c_float, c: *mut c_float,
bb: c_int, na: c_int, nb: c_int, nc: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_dspark_scatter_bf16(
src: *const c_float, dst: *mut u16, pos: *const c_int, m: c_int,
c: c_int, cap: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_embed_bf16_gather(
table: *const u16, tokens: *const i32, out: *mut c_float,
b: c_int, d: c_int, vocab: c_int, stream: *mut c_void,
@@ -519,6 +523,14 @@ pub fn dspark_split3(inp: &DeviceBuf, a: &DeviceBuf, b: &DeviceBuf, c: Option<&D
Ok(())
}
/// Scatter f32 src[m,C] into bf16 ring dst[cap,C] at slot pos[i]%cap (RNE).
#[cfg(feature = "hip")]
pub fn dspark_scatter_bf16(src: &DeviceBuf, dst: &DeviceBuf, pos: &DeviceBuf, m: i32, c: i32, cap: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_dspark_scatter_bf16(src.ptr as *const f32, dst.ptr as *mut u16, pos.ptr as *const i32, m, c, cap, std::ptr::null_mut()) };
if rc != 0 { return Err("dspark_scatter_bf16 launch failed".into()); }
Ok(())
}
/// Launch k_embed_bf16_gather: `b` token rows from BF16 table `[vocab, d]` → f32.
#[cfg(feature = "hip")]
pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, b: i32, d: i32, vocab: i32) -> Result<(), String> {
@@ -640,8 +652,12 @@ pub fn flash_swa_gqa_prefill_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, ou
let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let sk = sink_logit.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
// P1 b7: FA2 WMMA prefill (hd==128) keeps P in LDS -> no global scores_scratch.
if hd == 128 && std::env::var("VETTA_NO_FLASH_WMMA").is_err() {
// FA2 WMMA prefill (hd==128) is OPT-IN (VETTA_FLASH_WMMA=1): its online-softmax
// rescale over a mixed-position query tile makes a query's output depend on its
// batch neighbours by ~1 ulp (the masked extra KV block still rescales o_acc).
// That breaks speculative losslessness AND chunked-prefill determinism, so the
// default is the per-query-deterministic scalar f16 flash (verified baseline).
if hd == 128 && std::env::var("VETTA_FLASH_WMMA").is_ok() {
let rc = unsafe {
ffi::vetta_flash_swa_gqa_prefill_wmma(q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, pos.ptr as *const i32, rb, max_rel, sk, gt, m, std::ptr::null_mut())
};
@@ -1376,6 +1392,40 @@ mod gpu_tests {
eprintln!("shortconv4_hist_snaps: all {} prefixes exact", b + 1);
}
/// The DEFAULT flash path must be per-query deterministic across M: query0 at
/// pos12 in an M=2 batch (pos=[12,13]) must equal M=1 (pos=[12]) EXACTLY.
/// A divergence means a token's attention depends on its batch neighbours
/// (breaks spec losslessness AND chunked-prefill determinism).
#[test]
#[ignore]
fn flash_batch_determinism() {
let (n_head, n_kv, hd, seq) = (24usize, 8usize, 128usize, 512usize);
let f16 = |v: f32| -> u16 { let u = v.to_bits(); let s = ((u >> 16) & 0x8000) as u16; let e = ((u >> 23) & 0xff) as i32; let m = u & 0x7fffff; if e == 0 { return s; } let ne = e - 127 + 15; if ne <= 0 { return s; } if ne >= 31 { return s | 0x7c00; } s | ((ne as u16) << 10) | ((m >> 13) as u16) };
let q: Vec<f32> = (0..2 * n_head * hd).map(|i| ((i % 53) as f32 - 26.0) * 0.03).collect();
let mut k = vec![0u16; n_kv * seq * hd];
let mut v = vec![0u16; n_kv * seq * hd];
for kvh in 0..n_kv { for p in 0..14 { for dd in 0..hd {
k[(kvh * seq + p) * hd + dd] = f16(((p * 7 + dd * 3 + kvh) % 41) as f32 * 0.02 - 0.4);
v[(kvh * seq + p) * hd + dd] = f16(((p * 5 + dd * 11 + kvh) % 37) as f32 * 0.02 - 0.3);
} } }
let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); dq.h2d(&q).unwrap();
let dk = DeviceBuf::alloc(k.len() * 2).unwrap(); dk.h2d_bytes(bytemuck_u16(&k)).unwrap();
let dv = DeviceBuf::alloc(v.len() * 2).unwrap(); dv.h2d_bytes(bytemuck_u16(&v)).unwrap();
let scale = 1.0f32 / (hd as f32).sqrt();
let pos2 = DeviceBuf::alloc(8).unwrap(); pos2.h2d_bytes(&[12i32, 13].iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
let out2 = DeviceBuf::alloc(2 * n_head * hd * 4).unwrap();
flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &out2, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, 1024, &pos2, 13, None, 1024, None, None, 2).unwrap();
let mut o2 = vec![0f32; 2 * n_head * hd]; out2.d2h(&mut o2).unwrap();
let dq0 = DeviceBuf::alloc(n_head * hd * 4).unwrap(); dq0.h2d(&q[..n_head * hd]).unwrap();
let pos1 = DeviceBuf::alloc(4).unwrap(); pos1.h2d_bytes(&12i32.to_le_bytes()).unwrap();
let out1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
flash_swa_gqa_prefill_f16(&dq0, &dk, &dv, &out1, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, 1024, &pos1, 12, None, 1024, None, None, 1).unwrap();
let mut o1 = vec![0f32; n_head * hd]; out1.d2h(&mut o1).unwrap();
let md = o2[..n_head * hd].iter().zip(o1.iter()).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
eprintln!("flash_batch_determinism: query0 M=2 vs M=1 maxdiff={md:.3e}");
assert_eq!(&o2[..n_head * hd], &o1[..], "default flash query0 depends on batch neighbours");
}
fn f32_to_bf16(v: f32) -> u16 { let u = v.to_bits(); ((u + 0x7FFFu32 + ((u >> 16) & 1)) >> 16) as u16 }
fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) }