diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 64b3418..e8eac21 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -237,7 +237,7 @@ pub fn vec_add(a: &DeviceBuf, b: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result< Ok(()) } -/// Launch k_cast_f32_bf16: f32 activation -> BF16 (truncate). +/// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even). #[cfg(feature = "hip")] pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { let rc = unsafe { ffi::vetta_cast_f32_bf16(x.ptr as *const f32, y.ptr as *mut u16, n, std::ptr::null_mut()) }; @@ -410,7 +410,7 @@ mod gpu_tests { } } - fn f32_to_bf16(v: f32) -> u16 { (v.to_bits() >> 16) as u16 } + 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) } #[test] @@ -777,7 +777,7 @@ mod gpu_tests { let w = &sw[ch * 4..ch * 4 + 4]; want[ch] = (x0 + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0) * inv_sqrt5; } - for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = xs[t][ch]; } + for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_to_f32(f32_to_bf16(h1)); hist[c + ch] = bf16_to_f32(f32_to_bf16(h2)); hist[2 * c + ch] = bf16_to_f32(f32_to_bf16(xs[t][ch])); } // GPU step (hist evolves on device). dcur.h2d(&xs[t]).unwrap(); shortconv4_decode(&dcur, &dsw, &dh, &dout, &dslot, 1, c as i32).unwrap(); @@ -817,7 +817,7 @@ mod gpu_tests { let y = x0 + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0 + dt[0] * x0 + dt[1] * h2 + dt[2] * h1 + dt[3] * h0; want[ch] = y / 3.0; } - for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = xs[t][ch]; } + for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_to_f32(f32_to_bf16(h1)); hist[c + ch] = bf16_to_f32(f32_to_bf16(h2)); hist[2 * c + ch] = bf16_to_f32(f32_to_bf16(xs[t][ch])); } dcur.h2d(&xs[t]).unwrap(); ddyn.h2d(&dyns[t]).unwrap(); shortconv4_dyn_decode(&dcur, &dsw, &ddyn, &dh, &dout, &dslot, 1, c as i32, n_heads as i32).unwrap(); let mut got = vec![0f32; c]; dout.d2h(&mut got).unwrap(); @@ -969,7 +969,7 @@ mod gpu_tests { #[test] #[ignore] fn loop_controller_parity_vs_cpu() { - let bf = |x: f32| -> u16 { (x.to_bits() >> 16) as u16 }; + let bf = |x: f32| -> u16 { let u = x.to_bits(); ((u + 0x7FFFu32 + ((u >> 16) & 1)) >> 16) as u16 }; let ubf = |h: u16| -> f32 { f32::from_bits((h as u32) << 16) }; let trunc = |x: f32| -> f32 { ubf(bf(x)) }; let (d, gr) = (64usize, 8usize); diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 7028557..3020d74 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -382,7 +382,7 @@ pub fn forward_inkling_with_state( blocks.truncate(n_prelude_blocks); } for ip in 6..18 { - if p > 0 { + if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() { let mq = load_msg_queries(ar, ip, h)?; let n_bank = bank.len(); let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?; @@ -729,6 +729,7 @@ mod tests { let vocab = 201024usize; let prompt = "The capital of France is"; let ids: Vec = tok.encode(prompt, false).unwrap().get_ids().iter().map(|&x| x as i32).collect(); + eprintln!("[gen] prompt_ids={ids:?}"); let n_gen = 16usize; let max_seq = ids.len() + n_gen + 2; let mut states: Vec> = (0..24).map(|_| None).collect(); diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 96cafc1..f4d754c 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -271,7 +271,7 @@ mod tests { assert!(max_rel < 1e-3, "real expert MXFP8 parity failed: {max_rel}"); } - fn bf16_trunc(x: f32) -> f32 { f32::from_bits(x.to_bits() & 0xFFFF0000) } + fn bf16_trunc(x: f32) -> f32 { let u = x.to_bits(); let r = 0x7FFFu32 + ((u >> 16) & 1); f32::from_bits(((u + r) >> 16) << 16) } fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec { let d = x.len(); let ss: f32 = x.iter().map(|v| v * v).sum(); @@ -442,7 +442,7 @@ mod tests { let w = &sw[ch * 4..ch * 4 + 4]; y[ch] = (x0[ch] + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0[ch]) * inv; } - for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = x0[ch]; } + for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_trunc(h1); hist[c + ch] = bf16_trunc(h2); hist[2 * c + ch] = bf16_trunc(x0[ch]); } y } @@ -726,7 +726,7 @@ mod tests { let dt = &dyn_t[head * 4..head * 4 + 4]; y[ch] = (x0[ch] + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0[ch] + dt[0] * x0[ch] + dt[1] * h2 + dt[2] * h1 + dt[3] * h0) / 3.0; } - for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = x0[ch]; } + for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_trunc(h1); hist[c + ch] = bf16_trunc(h2); hist[2 * c + ch] = bf16_trunc(x0[ch]); } y } @@ -851,6 +851,7 @@ mod tests { let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize); let (qk_clip, rel_clip, eps) = (22.627416997969522f32, 8.0f32, 1e-6f32); let kv_dim = n_kv * hd; let q_dim = n_head * hd; + let scale = 1.0f32 / (hd as f32).sqrt(); let x: Vec = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect(); let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip, rel_clip, eps, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap(); @@ -904,5 +905,80 @@ mod tests { let k_cv_w = sconv_dyn_step(&k_raw_w, &ks_f, &k_dyn_w, &mut hk, kv_dim, n_kv); let mut gkc = vec![0f32; kv_dim]; k_cv.d2h(&mut gkc).unwrap(); cmp("k_dyn_sconv", &gkc, &k_cv_w); let mut gkd = vec![0f32; n_kv * 4]; k_dyn.d2h(&mut gkd).unwrap(); cmp("k_dyn_taps", &gkd, &k_dyn_w); + // ---- continue: V path + clips + attention + oproj + asc + cur + mlpin + MoE ---- + let v_raw = DeviceBuf::alloc(kv_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in2_bf, &lw.wv, &v_raw, 1, kv_dim as i32, hidden as i32).unwrap(); + let v_dyn = DeviceBuf::alloc(n_kv * 4 * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in2_bf, &lw.v_proj, &v_dyn, 1, (n_kv * 4) as i32, hidden as i32).unwrap(); + let histv = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); histv.h2d(&vec![0f32; 3 * kv_dim]).unwrap(); + let v_cv = DeviceBuf::alloc(kv_dim * 4).unwrap(); + vetta_infer_hip::shortconv4_dyn_decode(&v_raw, &lw.v_static, &v_dyn, &histv, &v_cv, &slot0, 1, kv_dim as i32, n_kv as i32).unwrap(); + let r_raw = DeviceBuf::alloc(n_head * d_rel * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.wr, &r_raw, 1, (n_head * d_rel) as i32, hidden as i32).unwrap(); + let gatea = DeviceBuf::alloc(q_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.wg, &gatea, 1, q_dim as i32, hidden as i32).unwrap(); + let sinks = DeviceBuf::alloc(n_head * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.ws, &sinks, 1, n_head as i32, hidden as i32).unwrap(); + vetta_infer_hip::l2_clip(&q, Some(&lw.q_sc), n_head as i32, hd as i32, qk_clip, true, 0).unwrap(); + vetta_infer_hip::l2_clip(&r_raw, Some(&lw.r_sc), n_head as i32, d_rel as i32, rel_clip, true, 0).unwrap(); + vetta_infer_hip::l2_clip(&k_cv, None, n_kv as i32, hd as i32, qk_clip, false, 0).unwrap(); + let rel_bias = DeviceBuf::alloc(n_head * rel_extent * 4).unwrap(); rel_bias.h2d(&vec![0f32; n_head * rel_extent]).unwrap(); + vetta_infer_hip::relpos_bias(&r_raw, &lw.rel_proj, &rel_bias, n_head as i32, d_rel as i32, rel_extent as i32, 1).unwrap(); + let kcache = DeviceBuf::alloc(n_kv * hd * 4).unwrap(); let vcache = DeviceBuf::alloc(n_kv * hd * 4).unwrap(); + vetta_infer_hip::kv_store(&k_cv, &v_cv, &kcache, &vcache, 0, n_kv as i32, hd as i32, 1, eps).unwrap(); + let aout = DeviceBuf::alloc(q_dim * 4).unwrap(); + vetta_infer_hip::flash_swa_gqa_decode(&q, &kcache, &vcache, &aout, n_head as i32, n_kv as i32, 1, hd as i32, scale, 0, 0, Some(&rel_bias), rel_extent as i32, Some(&sinks), Some(&gatea)).unwrap(); + let aout_bf = DeviceBuf::alloc(q_dim * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim).unwrap(); + let oproj = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::gemm_bf16(&aout_bf, &lw.wo, &oproj, 1, hidden as i32, q_dim as i32).unwrap(); + let hista = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hista.h2d(&vec![0f32; 3 * hidden]).unwrap(); + let asc = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::shortconv4_decode(&oproj, &lw.a_sconv, &hista, &asc, &slot0, 1, hidden as i32).unwrap(); + // CPU oracle for V/attention/asc + let in2_bf_w: Vec = _in2_w.iter().map(|&v| bf16_trunc(v)).collect(); + let wv_f = read_bf16_f32(&ar, &format!("{p}.wv_dv.weight")); + let wr_f = read_bf16_f32(&ar, &format!("{p}.wr_du.weight")); + let wg_f = read_bf16_f32(&ar, &format!("{p}.gate_attn.weight")); + let ws_f = read_bf16_f32(&ar, &format!("{p}.attn_sink_proj.weight")); + let wo_f = read_bf16_f32(&ar, &format!("{p}.wo_ud.weight")); + let vp_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight_proj")); + let vw_raw = read_bf16_f32(&ar, &format!("{p}.v_sconv.static_w")); + let mut vs_f = vec![0f32; kv_dim * 4]; for lag in 0..4 { for ch in 0..kv_dim { vs_f[ch * 4 + (3 - lag)] = vw_raw[lag * kv_dim + ch]; } } + let v_raw_w = proj_cpu(&in2_bf_w, &wv_f, kv_dim, hidden); + let v_dyn_w = proj_cpu(&in2_bf_w, &vp_f, n_kv * 4, hidden); + let mut hv = vec![0f32; 3 * kv_dim]; + let v_cv_w = sconv_dyn_step(&v_raw_w, &vs_f, &v_dyn_w, &mut hv, kv_dim, n_kv); + let mut gvc = vec![0f32; kv_dim]; v_cv.d2h(&mut gvc).unwrap(); cmp("v_dyn_sconv", &gvc, &v_cv_w); + let q_sc_f = read_bf16_f32(&ar, &format!("{p}.q_l2_clip.scale")); + let r_sc_f = read_bf16_f32(&ar, &format!("{p}.rel_l2_clip.scale")); + let rp_f = read_bf16_f32(&ar, &format!("{p}.rel_logits_proj.proj")); + let q_cl_w = l2_clip_cpu(&q_w, Some(&q_sc_f), n_head, hd, qk_clip); + let r_raw_w = proj_cpu(&in0_bf_w, &wr_f, n_head * d_rel, hidden); + let r_cl_w = l2_clip_cpu(&r_raw_w, Some(&r_sc_f), n_head, d_rel, rel_clip); + let k_cl_w = l2_clip_cpu(&k_cv_w, None, n_kv, hd, qk_clip); + let mut rb_w = vec![0f32; n_head * rel_extent]; + for h in 0..n_head { let mut acc = 0f32; for rc in 0..d_rel { acc += r_cl_w[h * d_rel + rc] * rp_f[rc * rel_extent]; } rb_w[h * rel_extent] = acc; } + let mut kc_w = vec![0f32; n_kv * hd]; let mut vc_w = vec![0f32; n_kv * hd]; + for h in 0..n_kv { let ss: f32 = (0..hd).map(|d| v_cv_w[h * hd + d] * v_cv_w[h * hd + d]).sum(); let fac = 1.0 / (ss / hd as f32 + eps).sqrt(); for d in 0..hd { kc_w[h * hd + d] = k_cl_w[h * hd + d]; vc_w[h * hd + d] = v_cv_w[h * hd + d] * fac; } } + let gatea_w = proj_cpu(&in0_bf_w, &wg_f, q_dim, hidden); + let sinks_w = proj_cpu(&in0_bf_w, &ws_f, n_head, hidden); + let mut aout_w = vec![0f32; q_dim]; + for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink = sinks_w[h]; let mut dot = 0f32; for d in 0..hd { dot += q_cl_w[h * hd + d] * kc_w[kvh * hd + d]; } dot = dot * scale + rb_w[h * rel_extent]; let m = sink.max(dot); let es = (dot - m).exp(); let denom = (sink - m).exp() + es; let inv = 1.0 / denom.max(1e-30); for d in 0..hd { let mut acc = es * inv * vc_w[kvh * hd + d]; acc *= 1.0 / (1.0 + (-gatea_w[h * hd + d]).exp()); aout_w[h * hd + d] = acc; } } + let mut gaout = vec![0f32; q_dim]; aout.d2h(&mut gaout).unwrap(); cmp("aout", &gaout, &aout_w); + let aout_bf_w: Vec = aout_w.iter().map(|&v| bf16_trunc(v)).collect(); + let oproj_w = proj_cpu(&aout_bf_w, &wo_f, hidden, q_dim); + let as_f = read_bf16_f32(&ar, &format!("{l}.attn_sconv.weight")); + let mut ha = vec![0f32; 3 * hidden]; + let asc_w = sconv_step(&oproj_w, &as_f, &mut ha, hidden); + let mut gasc = vec![0f32; hidden]; asc.d2h(&mut gasc).unwrap(); cmp("asc", &gasc, &asc_w); + let cur_c: Vec = x.iter().zip(&asc_w).map(|(a, b)| a + b).collect(); + let mut gcur = vec![0f32; hidden]; cur.d2h(&mut gcur).unwrap(); + // cur on GPU is still x (layer_forward not called); compute GPU cur = x + asc + let cur_gpu: Vec = x.iter().zip(&gasc).map(|(a, b)| a + b).collect(); + cmp("cur_after_attn", &cur_gpu, &cur_c); + let ss2: f32 = cur_c.iter().map(|v| v * v).sum(); let ir2 = 1.0 / (ss2 / hidden as f32 + eps).sqrt(); + let mix_c: Vec = cur_c.iter().map(|v| v * ir2).collect(); + let mn_f = read_bf16_f32(&ar, &format!("{l}.mlp_norm.weight")); + let mlpin_c = rms_norm_cpu(&mix_c, &mn_f, eps); + // GPU mlpin from cur_gpu + let curbuf = DeviceBuf::alloc(hidden * 4).unwrap(); curbuf.h2d(&cur_gpu).unwrap(); + let blk0 = DeviceBuf::alloc(hidden * 4).unwrap(); blk0.h2d(&vec![0f32; hidden]).unwrap(); + let mixg = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::attn_res_mix(&blk0, &curbuf, &lw.mlp_query, &mixg, 0, 1, 1, hidden as i32, eps).unwrap(); + let mlping = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::rms_norm_f32(&mixg, Some(&lw.mlp_norm), &mlping, 1, hidden as i32, eps).unwrap(); + let mut gmlpin = vec![0f32; hidden]; mlping.d2h(&mut gmlpin).unwrap(); cmp("mlpin", &gmlpin, &mlpin_c); + let _ = gcur; } } \ No newline at end of file diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index dbfae2a..2e16e50 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -110,6 +110,13 @@ __device__ __forceinline__ float bf16_to_f32(uint16_t h) { return __uint_as_float(((uint32_t)h) << 16); } +// round-to-nearest-even f32 -> bf16 -> f32 (exact strata f32_to_bf16 round trip). +__device__ __forceinline__ float bf16_round(float f) { + const uint32_t u = __float_as_uint(f); + const uint32_t r = 0x7FFFu + ((u >> 16) & 1u); + return __uint_as_float(((u + r) >> 16) << 16); +} + // ---- k_embed_bf16 (kernel #1): gather token rows from a BF16 table --------- // out[b, :] = bf16_to_f32(table[token[b], :]). Exact (no arithmetic). @@ -433,7 +440,12 @@ extern "C" int vetta_vec_add(const float* a, const float* b, float* y, size_t n, __global__ void k_cast_f32_bf16(const float* __restrict__ x, uint16_t* __restrict__ y, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; - if (i < n) y[i] = (uint16_t)(__float_as_uint(x[i]) >> 16); + if (i < n) { + // round-to-nearest-even (exact strata f32_to_bf16), NOT truncation. + const uint32_t u = __float_as_uint(x[i]); + const uint32_t rounding = 0x7FFFu + ((u >> 16) & 1u); + y[i] = (uint16_t)((u + rounding) >> 16); + } } extern "C" int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, @@ -644,9 +656,9 @@ __global__ void k_shortconv4_decode(const float* __restrict__ cur, const float* sw = static_w + (size_t)c * 4; float y = x0 + sw[0] * h0 + sw[1] * h1 + sw[2] * h2 + sw[3] * x0; y *= 0.44721359549995793f; // 1/sqrt(5) - h[0 * C + c] = h1; - h[1 * C + c] = h2; - h[2 * C + c] = x0; + h[0 * C + c] = bf16_round(h1); + h[1 * C + c] = bf16_round(h2); + h[2 * C + c] = bf16_round(x0); out[(size_t)m * C + c] = y; } @@ -688,9 +700,9 @@ __global__ void k_shortconv4_dyn_decode(const float* __restrict__ cur, const float* dt = dyn_taps + ((size_t)m * n_heads + head) * 4; y += dt[0] * x0 + dt[1] * h2 + dt[2] * h1 + dt[3] * h0; y *= (1.0f / 3.0f); - h[0 * C + c] = h1; - h[1 * C + c] = h2; - h[2 * C + c] = x0; + h[0 * C + c] = bf16_round(h1); + h[1 * C + c] = bf16_round(h2); + h[2 * C + c] = bf16_round(x0); out[(size_t)m * C + c] = y; } @@ -929,8 +941,10 @@ __global__ void k_ctrl_pack(const float* __restrict__ cur, const float* __restri __syncthreads(); const float ic = inv_c_s, im = inv_m_s; for (int d = tid; d < D; d += nt) { - packed[d] = (uint16_t)(__float_as_uint(cur[d] * ic) >> 16); - packed[D + d] = (uint16_t)(__float_as_uint(msg[d] * im) >> 16); + const uint32_t uc = __float_as_uint(cur[d] * ic); + const uint32_t um = __float_as_uint(msg[d] * im); + packed[d] = (uint16_t)((uc + 0x7FFFu + ((uc >> 16) & 1u)) >> 16); + packed[D + d] = (uint16_t)((um + 0x7FFFu + ((um >> 16) & 1u)) >> 16); } }