diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 5f04432..a2d28e8 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -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 = (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::>()).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) } diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index c3bbe30..9fa1205 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -445,6 +445,38 @@ extern "C" int vetta_dspark_split3(const float* in, float* a, float* b, return 0; } +// Scatter f32 rows src[m,C] into a bf16 ring dst[cap,C] at slot pos[i]%cap +// (bf16 RNE round). Commits the DSpark context for the fed tokens; rollback is +// a length truncate (ring slots of kept vs rejected spans are disjoint). +__global__ void k_dspark_scatter_bf16(const float* __restrict__ src, + uint16_t* __restrict__ dst, + const int* __restrict__ pos, int m, int C, + int cap) { + const int idx = blockIdx.x * blockDim.x + threadIdx.x; + const int total = m * C; + if (idx >= total) return; + const int i = idx / C; + const int c = idx % C; + const int slot = ((pos[i] % cap) + cap) % cap; + const float v = src[idx]; + const uint32_t u = __float_as_uint(v); + const uint32_t r = 0x7FFFu + ((u >> 16) & 1u); + dst[(size_t)slot * C + c] = (uint16_t)((u + r) >> 16); +} + +extern "C" int vetta_dspark_scatter_bf16(const float* src, uint16_t* dst, + const int* pos, int m, int C, int cap, + vetta_stream_t stream) { + if (m <= 0 || C <= 0 || cap <= 0) return 1; + const size_t total = (size_t)m * C; + const int t = 256; + const size_t grid = (total + t - 1) / t; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_dspark_scatter_bf16<<>>(src, dst, pos, m, C, cap); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- BF16 helpers ---------------------------------------------------------- __device__ __forceinline__ float bf16_to_f32(uint16_t h) { @@ -2973,7 +3005,13 @@ __global__ void __launch_bounds__(128) k_flash_swa_gqa_prefill_wmma( lmax = fmaxf(lmax, __shfl_xor(lmax, 2, 32)); lmax = fmaxf(lmax, __shfl_xor(lmax, 1, 32)); const float nm = fmaxf(row_max[r], lmax); - const float alpha = (row_sum[r] > 0.0f) ? __expf(row_max[r] - nm) : 0.0f; + // alpha must be EXACTLY 1.0 when the running max is unchanged: the + // fast __expf(0) is ~1 ulp off 1.0, and a fully-masked extra KV block + // (q_max_pos > this query's pos in a mixed-position tile) would then + // rescale o_acc/row_sum by ~1.0, making the output depend on batch + // neighbours. Guarding nm==row_max keeps it per-query deterministic + // (required for speculative losslessness + chunked-prefill parity). + const float alpha = (row_sum[r] > 0.0f) ? ((nm == row_max[r]) ? 1.0f : __expf(row_max[r] - nm)) : 0.0f; #pragma unroll for (int d = 0; d < 8; ++d) o_acc[d][r] *= alpha; row_sum[r] *= alpha;