[HIP][LD] softcap kernel + correct final output path (AttnRes output mix + softcap)

- k_softcap / vetta_softcap: logits = cap*tanh(x/cap), the final logit
  softcapping (Inkling cap=30). Parity vs CPU 9.7e-8; bounds |logits| <= cap.
- ld::layer::final_logits: the CORRECT final output path extracted from the
  reference — the final norm is itself an AttnRes depth mix over the block
  snapshots + cur with the learned output_query, then norm + unembed + softcap:
    h_norm = norm(attn_res_mix(blocks, cur, output_query))
    logits = softcap(unembed(h_norm), 30)
  (The earlier unembed_logits used a plain rms_norm(cur), missing the final
  depth mix; final_logits fixes that.)
- multi_layer_prelude_forward now uses final_logits: argmax token 128538
  (logit 19.16, bounded by 30). The token shifts vs the plain-norm path,
  confirming the final output mix materially affects the result.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU softcap + multi-layer final PASS
(--features hip, --ignored).
This commit is contained in:
adm committed 2026-12-01 14:51:40 +01:00
1 parent ff524df917
commit 2dd9ff952c
4 files changed
+65 -1

No files matched your search

+26
View File
@@ -67,6 +67,7 @@ mod ffi {
pub fn vetta_l2_clip(x: *mut c_float, scale: *const c_float, rows: c_int, hd: c_int, clip: c_float, apply_tau: c_int, pos: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, n_head: c_int, d_rel: c_int, rel_extent: c_int, lim: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store(k_in: *const c_float, v_in: *const c_float, k_cache: *mut c_float, v_cache: *mut c_float, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_softcap(x: *const c_float, y: *mut c_float, n: usize, cap: c_float, stream: *mut c_void) -> c_int;
}
}
@@ -309,6 +310,14 @@ pub fn kv_store(k_in: &DeviceBuf, v_in: &DeviceBuf, k_cache: &DeviceBuf, v_cache
Ok(())
}
/// Launch k_softcap: y = cap * tanh(x / cap).
#[cfg(feature = "hip")]
pub fn softcap(x: &DeviceBuf, y: &DeviceBuf, n: usize, cap: f32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_softcap(x.ptr as *const f32, y.ptr as *mut f32, n, cap, std::ptr::null_mut()) };
if rc != 0 { return Err("softcap launch failed".into()); }
Ok(())
}
#[cfg(all(test, feature = "hip"))]
mod gpu_tests {
use super::*;
@@ -864,6 +873,23 @@ mod gpu_tests {
eprintln!("k2 prep kernels (l2_clip + relpos_bias + kv_store): parity OK");
}
#[test]
#[ignore]
fn softcap_parity_vs_cpu() {
let cap = 30.0f32;
let n = 5000usize;
let x: Vec<f32> = (0..n).map(|i| ((i % 201) as f32 - 100.0) * 0.5).collect();
let want: Vec<f32> = x.iter().map(|&v| cap * (v / cap).tanh()).collect();
let dx = DeviceBuf::alloc(n * 4).unwrap(); dx.h2d(&x).unwrap();
let dy = DeviceBuf::alloc(n * 4).unwrap();
softcap(&dx, &dy, n, cap).unwrap();
let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap();
let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("softcap max_rel_err={mr:.3e}");
assert!(mr < 1e-5, "softcap parity failed: {mr}");
assert!(got.iter().all(|v| v.abs() <= cap + 1e-3), "softcap must bound logits");
}
fn bytemuck_u16(v: &[u16]) -> &[u8] {
unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) }
}
+19 -1
View File
@@ -241,6 +241,23 @@ pub fn unembed_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, hidden: usize, v
Ok(logits)
}
/// Correct final output path: the final norm is itself an AttnRes depth mix
/// (output_query over blocks + cur), then norm + unembed + logit softcap.
/// h_norm = norm(attn_res_mix(blocks, cur, output_query)); logits = softcap(unembed(h_norm)).
pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result<DeviceBuf, String> {
let oq = load_raw(ar, "model.llm.attn_res.output_query")?;
let n_blocks = blocks.len();
let blk = DeviceBuf::alloc(n_blocks.max(1) * hidden * 4)?;
let mut bh = vec![0f32; n_blocks.max(1) * hidden];
for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * hidden..(i + 1) * hidden])?; }
blk.h2d(&bh)?;
let mix = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::attn_res_mix(&blk, cur, &oq, &mix, n_blocks as i32, 1, 1, hidden as i32, eps)?;
let logits = unembed_logits(ar, &mix, hidden, vocab, eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
Ok(logits)
}
/// Run a schedule of SWA layer steps over an embedded token, returning the
/// final residual stream + the accumulated depth-block snapshots. (Prelude /
/// single-pass; full-attn layers + loop controllers + bank rollback come next.)
@@ -273,9 +290,10 @@ mod tests {
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 };
let (cur, blocks) = forward_swa_layers(&ar, &[0, 1, 2, 3, 4], &d, 100, 1, 0).unwrap();
assert_eq!(blocks.len(), 1, "prelude 0..4 snapshots only at ip=0");
let logits = unembed_logits(&ar, &cur, d.hidden, 201024, d.eps).unwrap();
let logits = final_logits(&ar, &cur, &blocks, d.hidden, 201024, d.eps, 30.0).unwrap();
let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap();
assert!(lg.iter().all(|v| v.is_finite()), "logits must be finite");
assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "softcap must bound logits");
let argmax = lg.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0;
eprintln!("multi-layer prelude (0..4) forward: argmax token={argmax} logit={:.3}", lg[argmax]);
assert!(argmax < 201024);
+3
View File
@@ -113,6 +113,9 @@ int vetta_kv_store(const float* k_in, const float* v_in, float* k_cache,
float* v_cache, int pos, int n_kv, int hd, int seq,
float rms_eps, vetta_stream_t stream);
// k_softcap: y = cap * tanh(x / cap) (final logit softcapping).
int vetta_softcap(const float* x, float* y, size_t n, float cap, vetta_stream_t stream);
// Core <15 microkernel entry points (implemented progressively in M1 & M2):
// 1. k_embed_bf16
// 2. k_rms_norm
+17
View File
@@ -795,3 +795,20 @@ extern "C" int vetta_kv_store(const float* k_in, const float* v_in, float* k_cac
HIP_CHECK(hipGetLastError());
return 0;
}
// ---- k_softcap: logits = cap * tanh(x / cap) (final logit softcapping) -----
__global__ void k_softcap(const float* __restrict__ x, float* __restrict__ y, size_t n, float cap) {
size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = cap * tanhf(x[i] / cap);
}
extern "C" int vetta_softcap(const float* x, float* y, size_t n, float cap, vetta_stream_t stream) {
if (n == 0) return 0;
if (cap <= 0.f) return 1;
const int nt = 256;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_softcap<<<(n + nt - 1) / nt, nt, 0, s>>>(x, y, n, cap);
HIP_CHECK(hipGetLastError());
return 0;
}