[LD] FULL Inkling-2-Mini forward runs end-to-end (loop + controllers + MXFP8)

The complete 48-visit Inkling forward now runs on real weights on gfx1150:
prelude [0,6) -> core [6,18) x3 passes (bank rollback + cross-pass msgs +
gain/forget controllers on passes 1,2) -> coda [18,24) -> final depth mix +
unembed + softcap. Produces finite, softcap-bounded logits over vocab 201024
(argmax 120533, logit 19.219) in ~1.9s.

- k_mxfp8_gemv / vetta_mxfp8_gemv + ue8m0_to_f32: MXFP8 experts (layers 20..23
  are F8_E4M3 + UE8M0/32, NOT NVFP4). y[n] = sum_k e4m3(W[n,k]) *
  ue8m0(scale[n,k/32]) * x[k], no outer scale. Real layer-20 expert parity
  1.45e-4 vs CPU dequant oracle. This is the engine-side per-layer precision
  composition: layers 0..19 NVFP4, 20..23 MXFP8, dispatched transparently.
- packer: ExpertMatrix.mxfp8 flag + load_expert_matrix auto-detects the format
  (amax tensor presence) + expert_gemv dispatch.
- ld::layer: ControllerWeights/load_controllers + apply_controller (RMS pack ->
  down GEMM -> gain/forget GEMM -> gating); LoopMsgs; layer_forward_swa/full
  take Option<(&ControllerWeights,&LoopMsgs)> (has_msgs path: 3 separate
  controlled inputs for SWA, controllers before attn norm / after mlp norm).
- is_swa + load_msg_queries (stacked cross-pass queries) + run_layer (SWA/full
  dispatch, persistent per-layer state across passes) + forward_inkling (the
  proven schedule from proofs/inkling_loop.lean, incl. bank rollback).
- full_inkling_forward_logits test: whole-model forward -> finite bounded logits.

NOTE: the forward RUNS and is bounded; bit-parity of the generated token vs the
reference engine is the next verification step (no correctness claim yet).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; GPU 18/18 + MXFP8 real parity + full forward PASS
(--features hip, --ignored).
This commit is contained in:
adm committed 2026-12-01 15:14:05 +01:00
1 parent 38ac957b26
commit 3c870743fe
5 files changed
+354 -33

No files matched your search

+71 -3
View File
@@ -43,10 +43,13 @@ pub struct ExpertMatrix {
pub outer: f32,
pub n: i32,
pub k: i32,
pub mxfp8: bool,
}
/// Load expert `e` of layer `layer`, matrix `mat` ("w13" or "w2"), from the
/// real safetensors archive. Zero requantization: bytes go to device as-is.
/// Layers 0..19 are NVFP4 (E2M1 + E4M3/16 + outer=amax/denom); layers 20..23
/// are MXFP8 (E4M3 + UE8M0/32, no outer). Detected by the amax tensor presence.
pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat: &str) -> Result<ExpertMatrix, String> {
let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}");
let wname = format!("{base}_weight");
@@ -56,8 +59,23 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
let winfo = ar.tensors.get(&wname).ok_or_else(|| format!("missing {wname}"))?;
let _sinfo = ar.tensors.get(&sname).ok_or_else(|| format!("missing {sname}"))?;
// w shape [n_exp, N, K/2]; scale [n_exp, N, K/16].
let n = winfo.shape[1] as i32;
if !ar.tensors.contains_key(&aname) {
// MXFP8: w [n_exp, N, K] full, scale [n_exp, N, K/32], no outer.
let k = winfo.shape[2] as i32;
let w_per_e = (n as usize) * (k as usize);
let s_per_e = (n as usize) * (k as usize / 32);
let mut wbytes = vec![0u8; w_per_e];
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
let mut sbytes = vec![0u8; s_per_e];
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
}
// NVFP4: w shape [n_exp, N, K/2]; scale [n_exp, N, K/16].
let k_half = winfo.shape[2] as usize;
let k = (k_half * 2) as i32;
let w_per_e = (n as usize) * k_half;
@@ -85,7 +103,16 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?;
scales.h2d_bytes(&sbytes)?;
Ok(ExpertMatrix { packed, scales, outer, n, k })
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
}
/// Run the expert GEMV dispatching on the quantization format (NVFP4 / MXFP8).
pub fn expert_gemv(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
if em.mxfp8 {
vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, x, y, em.n, em.k)
} else {
vetta_infer_hip::nvfp4_gemv(&em.packed, &em.scales, em.outer, x, y, em.n, em.k)
}
}
#[cfg(test)]
@@ -203,6 +230,47 @@ mod tests {
assert!(max_rel < 1e-3, "real expert NVFP4 parity failed: {max_rel}");
}
fn ue8m0(e: u8) -> f32 {
if e == 255 { return 0.0; }
if e == 0 { return f32::from_bits(0x00400000); }
f32::from_bits((e as u32) << 23)
}
/// Real MXFP8 expert GEMV parity (layers 20..23): load layer-20 expert-0
/// w13, run mxfp8_gemv on GPU, compare to a CPU dequant oracle (E4M3 weight
/// * UE8M0 scale per group of 32, no outer scale).
#[test]
#[ignore]
fn real_expert_mxfp8_gemv_parity() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let em = load_expert_matrix(&ar, 20, 0, "w13").unwrap();
assert!(em.mxfp8, "layer 20 must be MXFP8");
let (n, k) = (em.n as usize, em.k as usize);
assert_eq!((n, k), (2304, 2304));
let x: Vec<f32> = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
let dx = DeviceBuf::alloc(k * 4).unwrap(); dx.h2d(&x).unwrap();
let dy = DeviceBuf::alloc(n * 4).unwrap();
vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, &dx, &dy, em.n, em.k).unwrap();
let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap();
let mut wb = vec![0u8; n * k];
ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight", 0, &mut wb).unwrap();
let mut sb = vec![0u8; n * (k / 32)];
ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap();
let mut want = vec![0f32; n];
for ni in 0..n {
let mut acc = 0f32;
for b in 0..k / 32 {
let sc = ue8m0(sb[ni * (k / 32) + b]);
for j in 0..32 { acc += x[b * 32 + j] * e4m3(wb[ni * k + b * 32 + j]) * sc; }
}
want[ni] = acc;
}
let mut max_rel = 0f32;
for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("real expert w13 MXFP8 GEMV: max_rel_err={max_rel:.3e}");
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 rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
let d = x.len();
@@ -567,7 +635,7 @@ mod tests {
let mut st = crate::layer::new_state(&dims, steps).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos).unwrap();
crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();