[HIP] loop-controller kernels (RMS pack + gain/forget apply) verified

- k_ctrl_pack / vetta_ctrl_pack: exact strata k1_loop_ctrl_rms +
  k1_loop_ctrl_pack_in_bf16 — inv_c=rsqrt(mean(cur^2)+eps),
  inv_m=rsqrt(mean(msg^2)+eps); packed BF16 [2D] = [cur*inv_c ; msg*inv_m].
- k_ctrl_apply / vetta_ctrl_apply: exact k1_loop_ctrl_apply_out —
  out = (1-tanh(forget))*cur + tanh(gain)*msg (gain/forget gating of the loop
  message). The down/gain/forget low-rank projections reuse gemm_bf16.
- loop_controller_parity_vs_cpu: full controller chain (pack -> down GEMM
  [gate_rank] -> cast -> gain/forget GEMM [D] -> apply) vs a CPU oracle:
  max_rel_err 1.6e-7. The loop controller composes correctly.

This is the last kernel needed for the full Inkling forward. All mechanisms
(SWA + full-attn attention, MoE NVFP4, deep-residual block-mix, shortconv
static/dyn, loop controllers) are now verified microkernels.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; GPU 17/17 (--features hip).
This commit is contained in:
adm committed 2026-12-01 15:07:02 +01:00
1 parent 5ae2072981
commit 38ac957b26
3 files changed
+129

No files matched your search

+64
View File
@@ -69,6 +69,8 @@ mod ffi {
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;
pub fn vetta_ctrl_pack(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_apply(cur: *const c_float, msg: *const c_float, gain: *const c_float, forget: *const c_float, out: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
}
}
@@ -328,6 +330,22 @@ pub fn softcap(x: &DeviceBuf, y: &DeviceBuf, n: usize, cap: f32) -> Result<(), S
Ok(())
}
/// Launch k_ctrl_pack: RMS-normalize cur & msg -> packed BF16 [2D].
#[cfg(feature = "hip")]
pub fn ctrl_pack(cur: &DeviceBuf, msg: &DeviceBuf, packed: &DeviceBuf, d: i32, eps: f32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_ctrl_pack(cur.ptr as *const f32, msg.ptr as *const f32, packed.ptr as *mut u16, d, eps, std::ptr::null_mut()) };
if rc != 0 { return Err("ctrl_pack launch failed".into()); }
Ok(())
}
/// Launch k_ctrl_apply: out = (1-tanh(forget))*cur + tanh(gain)*msg.
#[cfg(feature = "hip")]
pub fn ctrl_apply(cur: &DeviceBuf, msg: &DeviceBuf, gain: &DeviceBuf, forget: &DeviceBuf, out: &DeviceBuf, n: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_ctrl_apply(cur.ptr as *const f32, msg.ptr as *const f32, gain.ptr as *const f32, forget.ptr as *const f32, out.ptr as *mut f32, n, std::ptr::null_mut()) };
if rc != 0 { return Err("ctrl_apply launch failed".into()); }
Ok(())
}
#[cfg(all(test, feature = "hip"))]
mod gpu_tests {
use super::*;
@@ -937,6 +955,52 @@ mod gpu_tests {
assert!(got.iter().all(|v| v.abs() <= cap + 1e-3), "softcap must bound logits");
}
#[test]
#[ignore]
fn loop_controller_parity_vs_cpu() {
let bf = |x: f32| -> u16 { (x.to_bits() >> 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);
let eps = 1e-6f32;
let cur: Vec<f32> = (0..d).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect();
let msg: Vec<f32> = (0..d).map(|i| ((i % 23) as f32 - 11.0) * 0.08).collect();
let down: Vec<u16> = (0..gr * 2 * d).map(|i| bf(((i % 31) as f32 - 15.0) * 0.02)).collect();
let gain_w: Vec<u16> = (0..d * gr).map(|i| bf(((i % 17) as f32 - 8.0) * 0.03)).collect();
let forget_w: Vec<u16> = (0..d * gr).map(|i| bf(((i % 19) as f32 - 9.0) * 0.03)).collect();
// GPU
let dc = DeviceBuf::alloc(d * 4).unwrap(); dc.h2d(&cur).unwrap();
let dm = DeviceBuf::alloc(d * 4).unwrap(); dm.h2d(&msg).unwrap();
let packed = DeviceBuf::alloc(2 * d * 2).unwrap();
ctrl_pack(&dc, &dm, &packed, d as i32, eps).unwrap();
let dd = DeviceBuf::alloc(down.len() * 2).unwrap(); dd.h2d_bytes(bytemuck_u16(&down)).unwrap();
let gate = DeviceBuf::alloc(gr * 4).unwrap();
gemm_bf16(&packed, &dd, &gate, 1, gr as i32, (2 * d) as i32).unwrap();
let gate_bf = DeviceBuf::alloc(gr * 2).unwrap(); cast_f32_bf16(&gate, &gate_bf, gr).unwrap();
let dg = DeviceBuf::alloc(gain_w.len() * 2).unwrap(); dg.h2d_bytes(bytemuck_u16(&gain_w)).unwrap();
let df = DeviceBuf::alloc(forget_w.len() * 2).unwrap(); df.h2d_bytes(bytemuck_u16(&forget_w)).unwrap();
let gain = DeviceBuf::alloc(d * 4).unwrap();
let forget = DeviceBuf::alloc(d * 4).unwrap();
gemm_bf16(&gate_bf, &dg, &gain, 1, d as i32, gr as i32).unwrap();
gemm_bf16(&gate_bf, &df, &forget, 1, d as i32, gr as i32).unwrap();
let out = DeviceBuf::alloc(d * 4).unwrap();
ctrl_apply(&dc, &dm, &gain, &forget, &out, d).unwrap();
let mut got = vec![0f32; d]; out.d2h(&mut got).unwrap();
// CPU oracle
let ic = 1.0 / (cur.iter().map(|v| v * v).sum::<f32>() / d as f32 + eps).sqrt();
let im = 1.0 / (msg.iter().map(|v| v * v).sum::<f32>() / d as f32 + eps).sqrt();
let mut pk = vec![0f32; 2 * d];
for i in 0..d { pk[i] = trunc(cur[i] * ic); pk[d + i] = trunc(msg[i] * im); }
let gate_c: Vec<f32> = (0..gr).map(|n| (0..2 * d).map(|k| pk[k] * ubf(down[n * 2 * d + k])).sum()).collect();
let gate_bf_c: Vec<f32> = gate_c.iter().map(|&v| trunc(v)).collect();
let gain_c: Vec<f32> = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(gain_w[i * gr + r])).sum()).collect();
let forget_c: Vec<f32> = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(forget_w[i * gr + r])).sum()).collect();
let want: Vec<f32> = (0..d).map(|i| (1.0 - forget_c[i].tanh()) * cur[i] + gain_c[i].tanh() * msg[i]).collect();
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!("loop_controller max_rel_err={mr:.3e}");
assert!(mr < 1e-4, "loop controller parity failed: {mr}");
}
fn bytemuck_u16(v: &[u16]) -> &[u8] {
unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) }
}
+8
View File
@@ -121,6 +121,14 @@ int vetta_kv_store(const float* k_in, const float* v_in, float* k_cache,
// 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);
// k_ctrl_pack: RMS-normalize cur & msg -> packed BF16 [2D] (loop controller input).
int vetta_ctrl_pack(const float* cur, const float* msg, uint16_t* packed, int D,
float eps, vetta_stream_t stream);
// k_ctrl_apply: out = (1-tanh(forget))*cur + tanh(gain)*msg (loop gating).
int vetta_ctrl_apply(const float* cur, const float* msg, const float* gain,
const float* forget, float* out, size_t n, vetta_stream_t stream);
// Core <15 microkernel entry points (implemented progressively in M1 & M2):
// 1. k_embed_bf16
// 2. k_rms_norm
+57
View File
@@ -856,4 +856,61 @@ extern "C" int vetta_softcap(const float* x, float* y, size_t n, float cap, vett
k_softcap<<<(n + nt - 1) / nt, nt, 0, s>>>(x, y, n, cap);
HIP_CHECK(hipGetLastError());
return 0;
}
// ---- k_ctrl_pack: loop-controller input pack (RMS-normalize cur & msg) -----
// Exact strata k1_loop_ctrl_rms + k1_loop_ctrl_pack_in_bf16: inv_c =
// rsqrt(mean(cur^2)+eps), inv_m = rsqrt(mean(msg^2)+eps); packed_bf16 [2D] =
// [cur*inv_c ; msg*inv_m] (BF16 truncate). One block per token.
__global__ void k_ctrl_pack(const float* __restrict__ cur, const float* __restrict__ msg,
uint16_t* __restrict__ packed, int D, float eps) {
const int tid = threadIdx.x;
const int nt = blockDim.x;
__shared__ float red[256];
__shared__ float inv_c_s, inv_m_s;
float ssc = 0.f, ssm = 0.f;
for (int d = tid; d < D; d += nt) { ssc += cur[d] * cur[d]; ssm += msg[d] * msg[d]; }
red[tid] = ssc; __syncthreads();
for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); }
if (tid == 0) inv_c_s = rsqrtf(red[0] / (float)D + eps);
__syncthreads();
red[tid] = ssm; __syncthreads();
for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); }
if (tid == 0) inv_m_s = rsqrtf(red[0] / (float)D + eps);
__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);
}
}
extern "C" int vetta_ctrl_pack(const float* cur, const float* msg, uint16_t* packed,
int D, float eps, vetta_stream_t stream) {
if (D <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_ctrl_pack<<<1, 256, 0, s>>>(cur, msg, packed, D, eps);
HIP_CHECK(hipGetLastError());
return 0;
}
// ---- k_ctrl_apply: out = (1 - tanh(forget))*cur + tanh(gain)*msg -----------
// Exact strata k1_loop_ctrl_apply_out (gain/forget gating of the loop message).
__global__ void k_ctrl_apply(const float* __restrict__ cur, const float* __restrict__ msg,
const float* __restrict__ gain, const float* __restrict__ forget,
float* __restrict__ out, size_t n) {
size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = (1.f - tanhf(forget[i])) * cur[i] + tanhf(gain[i]) * msg[i];
}
extern "C" int vetta_ctrl_apply(const float* cur, const float* msg, const float* gain,
const float* forget, float* out, size_t n, vetta_stream_t stream) {
if (n == 0) return 0;
const int nt = 256;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_ctrl_apply<<<(n + nt - 1) / nt, nt, 0, s>>>(cur, msg, gain, forget, out, n);
HIP_CHECK(hipGetLastError());
return 0;
}