[LD] FULL real Inkling layer end-to-end — deep-residual block-mix cadence verified

- real_full_layer_end_to_end test: a complete Inkling layer-0 (SWA, ip=0) runs
  end-to-end on real weights with the EXACT deep-residual cadence:
    in0 = attn_norm(cur)                 (ip==0: no attention mix)
    asc = attention block(in0)           (projections..flash SWA..O-proj..sconv)
    ip%block_size(6)==0: block0 <- cur; cur = asc   (snapshot + replace)
    mlpin = mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
    moeout = MoE block(mlpin)            (router..8 NVFP4 experts..reduce)
    cur += mlp_sconv(moeout)             (MoE residual is a plain add)
- Extracted the exact residual rules from the reference: the AttnRes block
  snapshot/replace applies ONLY to the attention output (ip%6==0 snapshots cur
  then cur=asc, else cur+=asc); the MoE output is always a plain residual add.
  The MoE input is a learned AttnRes mix over block snapshots + cur (mlp_queries).
- Parity vs a full CPU oracle (incl. the block-mix softmax over depth states):
  max_rel_err 6.6e-4, router experts [116,69,124,72,18,64,106,0]. A complete
  real Inkling layer now composes correctly — the deep residual is not a plain
  add but the learned block mixture, reproduced exactly.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real full layer PASS
(--features hip, --ignored).
This commit is contained in:
adm committed 2026-12-01 14:43:01 +01:00
1 parent 77c86535d0
commit 25ffc820f8
1 file changed
+208
+208
View File
@@ -536,4 +536,212 @@ mod tests {
assert!(mr < 3e-3, "real attention block step {t} parity failed: {mr}");
}
}
/// FULL REAL LAYER (ip=0, SWA layer 0) end-to-end: attention block + AttnRes
/// block snapshot (block_size=6) + MoE block + residual, with the exact
/// Inkling deep-residual cadence:
/// in0 = attn_norm(cur) (ip==0: no attention mix)
/// asc = attn_block(in0) (projections..flash..O-proj..sconv)
/// ip%6==0: block0 <- cur; cur = asc
/// mlpin = mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
/// moeout = moe_block(mlpin)
/// cur += mlp_sconv(moeout) (MoE residual is a plain add)
/// Parity vs a full CPU oracle.
#[test]
#[ignore]
fn real_full_layer_end_to_end() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let p = "model.llm.layers.0.attn";
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
let (inter, n_experts, top_k) = (1152usize, 128usize, 8usize);
let (qk_clip, rel_clip, eps, route_scale) = (22.627416997969522f32, 8.0f32, 1e-6f32, 8.0f32);
let (beta, lb) = (4.0f32, 25.0f32);
let kv_dim = n_kv * hd; let q_dim = n_head * hd;
let scale = 1.0f32 / (hd as f32).sqrt();
let pos = 0i32; let steps = 1usize;
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
// attention weights (device)
let attn_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_norm.weight").unwrap();
let wq = load_raw(&ar, &format!("{p}.wq_du.weight")).unwrap();
let wk = load_raw(&ar, &format!("{p}.wk_dv.weight")).unwrap();
let wv = load_raw(&ar, &format!("{p}.wv_dv.weight")).unwrap();
let wr = load_raw(&ar, &format!("{p}.wr_du.weight")).unwrap();
let wg = load_raw(&ar, &format!("{p}.gate_attn.weight")).unwrap();
let ws = load_raw(&ar, &format!("{p}.attn_sink_proj.weight")).unwrap();
let wo = load_raw(&ar, &format!("{p}.wo_ud.weight")).unwrap();
let q_sc = load_bf16_as_f32(&ar, &format!("{p}.q_l2_clip.scale")).unwrap();
let r_sc = load_bf16_as_f32(&ar, &format!("{p}.rel_l2_clip.scale")).unwrap();
let rel_proj = load_bf16_as_f32(&ar, &format!("{p}.rel_logits_proj.proj")).unwrap();
let k_sconv = load_bf16_as_f32(&ar, &format!("{p}.k_sconv.weight")).unwrap();
let v_sconv = load_bf16_as_f32(&ar, &format!("{p}.v_sconv.weight")).unwrap();
let a_sconv = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_sconv.weight").unwrap();
// MoE weights (device)
let mlp_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.mlp_norm.weight").unwrap();
let gate_w = load_raw(&ar, "model.llm.layers.0.mlp.gate.weight").unwrap();
let gate_b = load_raw(&ar, "model.llm.layers.0.mlp.gate.bias").unwrap();
let m_sconv = load_bf16_as_f32(&ar, "model.llm.layers.0.mlp_sconv.weight").unwrap();
let mlp_query = load_raw(&ar, "model.llm.attn_res.mlp_queries.0").unwrap(); // F32 [2304]
// scratch + state
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let in0 = DeviceBuf::alloc(hidden * 4).unwrap();
let in0_bf = DeviceBuf::alloc(hidden * 2).unwrap();
let q = DeviceBuf::alloc(q_dim * 4).unwrap();
let k_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let r_raw = DeviceBuf::alloc(n_head * d_rel * 4).unwrap();
let gatea = DeviceBuf::alloc(q_dim * 4).unwrap();
let sinks = DeviceBuf::alloc(n_head * 4).unwrap();
let k_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let hist_k = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_k.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_v = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_v.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_a = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hist_a.h2d(&vec![0f32; 3 * hidden]).unwrap();
let hist_m = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hist_m.h2d(&vec![0f32; 3 * hidden]).unwrap();
let rel_bias = DeviceBuf::alloc(n_head * rel_extent * 4).unwrap(); rel_bias.h2d(&vec![0f32; n_head * rel_extent]).unwrap();
let k_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); k_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let v_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); v_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let aout = DeviceBuf::alloc(q_dim * 4).unwrap();
let aout_bf = DeviceBuf::alloc(q_dim * 2).unwrap();
let oproj = DeviceBuf::alloc(hidden * 4).unwrap();
let asc = DeviceBuf::alloc(hidden * 4).unwrap();
let block0 = DeviceBuf::alloc(hidden * 4).unwrap();
let mix_out = DeviceBuf::alloc(hidden * 4).unwrap();
let mlpin = DeviceBuf::alloc(hidden * 4).unwrap();
let mlpin_bf = DeviceBuf::alloc(hidden * 2).unwrap();
let rlog = DeviceBuf::alloc(n_experts * 4).unwrap();
let ids = DeviceBuf::alloc(top_k * 4).unwrap();
let weights = DeviceBuf::alloc(top_k * 4).unwrap();
let gu = DeviceBuf::alloc(2 * inter * 4).unwrap();
let act = DeviceBuf::alloc(inter * 4).unwrap();
let moeout = DeviceBuf::alloc(hidden * 4).unwrap();
let msc = DeviceBuf::alloc(hidden * 4).unwrap();
let slot0 = DeviceBuf::alloc(4).unwrap(); slot0.h2d_bytes(&0i32.to_le_bytes()).unwrap();
// === GPU full layer ===
// attention input: ip==0 -> attn_norm(cur)
vetta_infer_hip::rms_norm_f32(&cur, Some(&attn_norm), &in0, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, hidden).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wq, &q, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wk, &k_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wv, &v_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wr, &r_raw, 1, (n_head * d_rel) as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wg, &gatea, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &ws, &sinks, 1, n_head as i32, hidden as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&k_raw, &k_sconv, &hist_k, &k_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&v_raw, &v_sconv, &hist_v, &v_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::l2_clip(&q, Some(&q_sc), n_head as i32, hd as i32, qk_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&r_raw, Some(&r_sc), n_head as i32, d_rel as i32, rel_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&k_cv, None, n_kv as i32, hd as i32, qk_clip, false, pos).unwrap();
vetta_infer_hip::relpos_bias(&r_raw, &rel_proj, &rel_bias, n_head as i32, d_rel as i32, rel_extent as i32, 1).unwrap();
vetta_infer_hip::kv_store(&k_cv, &v_cv, &k_cache, &v_cache, pos, n_kv as i32, hd as i32, steps as i32, eps).unwrap();
vetta_infer_hip::flash_swa_gqa_decode(&q, &k_cache, &v_cache, &aout, n_head as i32, n_kv as i32, steps as i32, hd as i32, scale, 1024, pos, Some(&rel_bias), rel_extent as i32, Some(&sinks), Some(&gatea)).unwrap();
vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim).unwrap();
vetta_infer_hip::gemm_bf16(&aout_bf, &wo, &oproj, 1, hidden as i32, q_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&oproj, &a_sconv, &hist_a, &asc, &slot0, 1, hidden as i32).unwrap();
// block rule ip%6==0: block0 <- cur; cur = asc
let mut cur_host = vec![0f32; hidden]; cur.d2h(&mut cur_host).unwrap();
block0.h2d(&cur_host).unwrap();
let mut asc_host = vec![0f32; hidden]; asc.d2h(&mut asc_host).unwrap();
cur.h2d(&asc_host).unwrap();
// MoE input: mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
vetta_infer_hip::attn_res_mix(&block0, &cur, &mlp_query, &mix_out, 1, 1, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::rms_norm_f32(&mix_out, Some(&mlp_norm), &mlpin, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::cast_f32_bf16(&mlpin, &mlpin_bf, hidden).unwrap();
vetta_infer_hip::gemm_bf16(&mlpin_bf, &gate_w, &rlog, 1, n_experts as i32, hidden as i32).unwrap();
vetta_infer_hip::moe_router_topk(&rlog, Some(&gate_b), &ids, &weights, 1, n_experts as i32, top_k as i32, route_scale).unwrap();
let ids_host = { let mut b = vec![0u8; top_k * 4]; ids.d2h_bytes(&mut b).unwrap(); b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>() };
let mut y_part_host = vec![0f32; top_k * hidden];
for kk in 0..top_k {
let e = ids_host[kk] as usize;
let w13 = load_expert_matrix(&ar, 0, e, "w13").unwrap();
vetta_infer_hip::nvfp4_gemv(&w13.packed, &w13.scales, w13.outer, &mlpin, &gu, w13.n, w13.k).unwrap();
vetta_infer_hip::situ(&gu, &act, inter as i32, beta, lb).unwrap();
let w2 = load_expert_matrix(&ar, 0, e, "w2").unwrap();
let ye = DeviceBuf::alloc(hidden * 4).unwrap();
vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k).unwrap();
ye.d2h(&mut y_part_host[kk * hidden..(kk + 1) * hidden]).unwrap();
}
let y_part = DeviceBuf::alloc(top_k * hidden * 4).unwrap(); y_part.h2d(&y_part_host).unwrap();
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, top_k as i32, hidden as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&moeout, &m_sconv, &hist_m, &msc, &slot0, 1, hidden as i32).unwrap();
vetta_infer_hip::vec_add(&cur, &msc, &cur, hidden).unwrap();
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// === CPU oracle ===
let an_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_norm.weight");
let wq_f = read_bf16_f32(&ar, &format!("{p}.wq_du.weight"));
let wk_f = read_bf16_f32(&ar, &format!("{p}.wk_dv.weight"));
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 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 ks_f = read_bf16_f32(&ar, &format!("{p}.k_sconv.weight"));
let vs_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight"));
let as_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_sconv.weight");
let mn_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp_norm.weight");
let ms_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp_sconv.weight");
let mq_f = { let mut b = vec![0u8; hidden * 4]; ar.read_slice("model.llm.attn_res.mlp_queries.0", 0, &mut b).unwrap(); b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<f32>>() };
let mut hk = vec![0f32; 3 * kv_dim]; let mut hv = vec![0f32; 3 * kv_dim]; let mut ha = vec![0f32; 3 * hidden]; let mut hm = vec![0f32; 3 * hidden];
let mut cur_c = x.clone();
let in0_c = rms_norm_cpu(&cur_c, &an_f, eps);
let in0_bf_c: Vec<f32> = in0_c.iter().map(|&v| bf16_trunc(v)).collect();
let q_c = proj_cpu(&in0_bf_c, &wq_f, q_dim, hidden);
let k_raw_c = proj_cpu(&in0_bf_c, &wk_f, kv_dim, hidden);
let v_raw_c = proj_cpu(&in0_bf_c, &wv_f, kv_dim, hidden);
let r_raw_c = proj_cpu(&in0_bf_c, &wr_f, n_head * d_rel, hidden);
let gatea_c = proj_cpu(&in0_bf_c, &wg_f, q_dim, hidden);
let sinks_c = proj_cpu(&in0_bf_c, &ws_f, n_head, hidden);
let k_cv_c = sconv_step(&k_raw_c, &ks_f, &mut hk, kv_dim);
let v_cv_c = sconv_step(&v_raw_c, &vs_f, &mut hv, kv_dim);
let q_cl = l2_clip_cpu(&q_c, Some(&q_sc_f), n_head, hd, qk_clip);
let r_cl = l2_clip_cpu(&r_raw_c, Some(&r_sc_f), n_head, d_rel, rel_clip);
let k_cl = l2_clip_cpu(&k_cv_c, None, n_kv, hd, qk_clip);
let mut rb_c = 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[h * d_rel + rc] * rp_f[rc * rel_extent]; } rb_c[h * rel_extent] = acc; }
let mut kc = vec![0f32; n_kv * hd]; let mut vc = vec![0f32; n_kv * hd];
for h in 0..n_kv { let ss: f32 = (0..hd).map(|d| v_cv_c[h * hd + d] * v_cv_c[h * hd + d]).sum(); let fac = 1.0 / (ss / hd as f32 + eps).sqrt(); for d in 0..hd { kc[h * hd + d] = k_cl[h * hd + d]; vc[h * hd + d] = v_cv_c[h * hd + d] * fac; } }
// flash at pos=0 (single position) + sink
let mut aout_c = vec![0f32; q_dim];
for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink = sinks_c[h]; let mut dot = 0f32; for d in 0..hd { dot += q_cl[h * hd + d] * kc[kvh * hd + d]; } dot = dot * scale + rb_c[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[kvh * hd + d]; acc *= 1.0 / (1.0 + (-gatea_c[h * hd + d]).exp()); aout_c[h * hd + d] = acc; } }
let aout_bf_c: Vec<f32> = aout_c.iter().map(|&v| bf16_trunc(v)).collect();
let oproj_c = proj_cpu(&aout_bf_c, &wo_f, hidden, q_dim);
let asc_c = sconv_step(&oproj_c, &as_f, &mut ha, hidden);
// block rule: block0 = cur_c; cur_c = asc_c
let block0_c = cur_c.clone();
cur_c = asc_c;
// mix([block0], cur, mlp_query) then mlp_norm
let mix_c = {
let states = [&block0_c, &cur_c];
let mut scores = [0f32; 2]; let mut irs = [0f32; 2];
let inv_sqrt_d = 1.0 / (hidden as f32).sqrt();
for s in 0..2 { let sv = states[s]; let ss: f32 = sv.iter().map(|v| v * v).sum(); let dot: f32 = sv.iter().zip(&mq_f).map(|(v, q)| v * q).sum(); let ir = 1.0 / (ss / hidden as f32 + eps).sqrt(); irs[s] = ir; scores[s] = dot * ir * inv_sqrt_d; }
let mx = scores[0].max(scores[1]); let e0 = (scores[0] - mx).exp(); let e1 = (scores[1] - mx).exp(); let sum = e0 + e1;
let w0 = e0 / sum * irs[0]; let w1 = e1 / sum * irs[1];
(0..hidden).map(|d| w0 * block0_c[d] + w1 * cur_c[d]).collect::<Vec<f32>>()
};
let mlpin_c = rms_norm_cpu(&mix_c, &mn_f, eps);
let mlpin_bf_c: Vec<f32> = mlpin_c.iter().map(|&v| bf16_trunc(v)).collect();
let gw_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp.gate.weight");
let rlog_c = proj_cpu(&mlpin_bf_c, &gw_f, n_experts, hidden);
let mut gb = vec![0u8; n_experts * 4]; ar.read_slice("model.llm.layers.0.mlp.gate.bias", 0, &mut gb).unwrap();
let bias_c: Vec<f32> = gb.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let prob: Vec<f32> = rlog_c.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect();
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias_c[e]).collect();
let mut ids_c = vec![0usize; top_k]; let mut w_c = vec![0f32; top_k]; let mut wsum = 0f32;
for kk in 0..top_k { let mut bv = f32::NEG_INFINITY; let mut bi = 0; for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } } ids_c[kk] = bi; w_c[kk] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30; }
let inv = route_scale / (wsum + 1e-20); for kk in 0..top_k { w_c[kk] *= inv; }
let mut moeout_c = vec![0f32; hidden];
for kk in 0..top_k { let e = ids_c[kk]; let o13 = expert_outer(&ar, 0, e, "w13"); let gu_c = nvfp4_gemv_cpu(&ar, 0, e, "w13", &mlpin_c, 2 * inter, hidden, o13); let act_c = situ_cpu(&gu_c, inter, beta, lb); let o2 = expert_outer(&ar, 0, e, "w2"); let ye_c = nvfp4_gemv_cpu(&ar, 0, e, "w2", &act_c, hidden, inter, o2); for d in 0..hidden { moeout_c[d] += w_c[kk] * ye_c[d]; } }
let msc_c = sconv_step(&moeout_c, &ms_f, &mut hm, hidden);
let want: Vec<f32> = (0..hidden).map(|d| cur_c[d] + msc_c[d]).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!("REAL full layer (ip=0): experts={:?} max_rel_err={mr:.3e}", ids_c);
assert!(mr < 3e-3, "real full layer parity failed: {mr}");
}
}