[Core] forward_batch: batched prefill orchestration (M=B) BIT-EXACT end-to-end

forward_batch embeds B tokens and runs the proven schedule (inkling_loop.lean)
at M=B: prelude [0,6) -> core [6,18) x3 with DEVICE-SIDE bank rollback (arena
sub-range via copy_f32_sub, cur<-prelude copy, blocks.truncate) + cross-pass
msgs (attn_res_mix over bank, nq=4) + controllers on passes 1,2 -> coda [18,24)
-> final depth mix + unembed LAST token. run_layer_batched dispatches SWA/full.
No host D2H/H2D gather anywhere in the batched path (graph-capturable shape).

copy_f32_sub: device f32 copy from src offset (extract bank / last token).

forward_batch_parity (real weights, B=4, f16 KV + device MoE): logits for the
last token BIT-EXACT (max_abs=0.0) AND argmax identical (111) vs 4 sequential
forward_inkling_with_state calls. The full batched prefill is verified.
This commit is contained in:
adm committed 2026-12-02 00:27:42 +01:00
1 parent 1aaf7f12c2
commit b41a71f2f7
2 files changed
+136

No files matched your search

+11
View File
@@ -480,6 +480,17 @@ pub fn gather_channel(msgs: &DeviceBuf, dst: &DeviceBuf, ch: i32, b: i32, h: i32
Ok(()) Ok(())
} }
/// Device-side f32 copy from `src` at element offset `src_offset` -> dst[0..n]
/// (extract a contiguous arena sub-range, e.g. the core-loop bank or last token).
#[cfg(feature = "hip")]
pub fn copy_f32_sub(src: &DeviceBuf, src_offset: usize, dst: &DeviceBuf, n: usize) -> Result<(), String> {
if src_offset * 4 + n * 4 > src.bytes { return Err("copy_f32_sub overflow".into()); }
let src_ptr = unsafe { (src.ptr as *const f32).add(src_offset) };
let rc = unsafe { ffi::vetta_copy_f32(src_ptr, dst.ptr as *mut f32, n, std::ptr::null_mut()) };
if rc != 0 { return Err("copy_f32_sub launch failed".into()); }
Ok(())
}
/// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even). /// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even).
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> {
+125
View File
@@ -917,6 +917,98 @@ pub fn forward_inkling_with_state(
out out
} }
/// Batched layer dispatcher (M=B): lazily allocates the per-layer state (core 3
/// passes, prelude/coda 1) and runs the SWA or full-attn batched layer.
#[allow(dead_code)] // wired by forward_batch
fn run_layer_batched(
cache: &WeightCache, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut BatchBlocks,
states: &mut [Option<LayerState>], max_seq: usize, pos: &DeviceBuf, max_pos: i32,
pass: usize, b: i32, ctrl: Option<(&ControllerWeights, &DeviceBuf)>,
) -> Result<(), String> {
if states[ip].is_none() {
let n_passes = if (6..18).contains(&ip) { 3 } else { 1 };
states[ip] = Some(new_state(d, max_seq, n_passes)?);
}
let st = states[ip].as_mut().unwrap();
if is_swa(ip) {
let w = cache.swa_layer(ip)?;
layer_forward_swa_batched(cache, &w, st, d, cur, blocks, pos, max_pos, pass, b, ctrl)
} else {
let w = cache.full_layer(ip, d)?;
layer_forward_full_batched(cache, &w, st, d, cur, blocks, pos, max_pos, pass, b, ctrl)
}
}
/// Batched prefill forward (M=B): embed B tokens, run the proven schedule
/// (proofs/inkling_loop.lean) prelude [0,6) -> core [6,18) x3 (bank rollback +
/// cross-pass msgs + controllers on passes 1,2) -> coda [18,24) -> final depth
/// mix + unembed, returning logits [vocab] for the LAST token. The depth-block
/// arena is device-resident (snapshot/rollback via device copy, no host gather).
/// `states` persists KV/history across the B positions (and across decode steps).
#[allow(dead_code)] // wired by serve prefill (next brick)
pub fn forward_batch(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
let h = d.hidden; let bu = tokens.len();
if bu == 0 { return Err("forward_batch: empty tokens".into()); }
let b = bu as i32;
let max_pos = base_pos + b - 1;
// Embed B tokens (gather + RMS-norm rows=B).
let table = cache.raw("model.llm.embed.weight")?;
let tok_bytes: Vec<u8> = tokens.iter().flat_map(|t| t.to_le_bytes()).collect();
let dtok = DeviceBuf::alloc(bu * 4)?; dtok.h2d_bytes(&tok_bytes)?;
let cur = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::embed_bf16_gather(&table, &dtok, &cur, b, h as i32, vocab as i32)?;
let emb_norm = cache.bf16_f32("model.llm.embed_norm.weight")?;
vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, b, h as i32, 1e-6)?;
let pos: Vec<i32> = (0..bu).map(|m| base_pos + m as i32).collect();
let pos_bytes: Vec<u8> = pos.iter().flat_map(|p| p.to_le_bytes()).collect();
let dpos = DeviceBuf::alloc(bu * 4)?; dpos.h2d_bytes(&pos_bytes)?;
let mut blocks = BatchBlocks::new(bu, h, 8)?;
// Prelude.
for ip in 0..6 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
let n_prelude_blocks = blocks.count;
let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?;
// Core: 3 passes with device-side bank rollback.
let no_ctrl = std::env::var("VETTA_NO_CTRL").is_ok();
for p in 0..3 {
let bank_out = DeviceBuf::alloc(bu * h * 4)?;
let mut bank_buf = DeviceBuf::alloc(bu * h * 4)?;
let mut n_bank = 0usize;
if p > 0 {
// bank = core block snapshots of the previous pass (skip the first).
n_bank = blocks.count.saturating_sub(n_prelude_blocks + 1);
bank_buf = DeviceBuf::alloc(n_bank.max(1) * bu * h * 4)?;
if n_bank > 0 { vetta_infer_hip::copy_f32_sub(&blocks.arena, (n_prelude_blocks + 1) * bu * h, &bank_buf, n_bank * bu * h)?; }
vetta_infer_hip::copy_f32(&cur, &bank_out, bu * h)?;
vetta_infer_hip::copy_f32(&prelude, &cur, bu * h)?; // rollback to prelude residual
blocks.truncate(n_prelude_blocks);
}
for ip in 6..18 {
if p > 0 && !no_ctrl {
let mq = load_msg_queries(cache, ip, h)?;
let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?;
vetta_infer_hip::attn_res_mix(&bank_buf, &bank_out, &mq, &msgs_buf, n_bank as i32, b, 4, h as i32, d.eps)?;
let cw = cache.controllers(ip)?;
run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, p, b, Some((&cw, &msgs_buf)))?;
} else {
run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, p, b, None)?;
}
}
}
// Coda.
for ip in 18..24 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
// Final depth mix + unembed the LAST token.
let oq = cache.raw("model.llm.attn_res.output_query")?;
let mix = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::attn_res_mix(&blocks.arena, &cur, &oq, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?;
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?;
let logits = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
Ok(logits)
}
thread_local! { thread_local! {
static EXPERT_NS: std::cell::Cell<u128> = const { std::cell::Cell::new(0) }; static EXPERT_NS: std::cell::Cell<u128> = const { std::cell::Cell::new(0) };
} }
@@ -1563,4 +1655,37 @@ mod tests {
assert!(max_rel < 3e-3, "batched full layer cur parity failed: {max_rel}"); assert!(max_rel < 3e-3, "batched full layer cur parity failed: {max_rel}");
assert!(kv_match, "batched full layer KV cache must be byte-identical"); assert!(kv_match, "batched full layer KV cache must be byte-identical");
} }
/// End-to-end batched prefill parity: forward_batch(B tokens) logits for the
/// LAST token vs B sequential forward_inkling_with_state calls (states persist).
/// Real weights, f16 KV + device MoE aligned. Checks argmax AND logit error.
#[test]
#[ignore]
fn forward_batch_parity() {
set_kv_f16(true);
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let cache = WeightCache::new(ar.clone());
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 vocab = 200058usize; let b = 4usize; let max_seq = b + 2;
let tokens: Vec<i32> = vec![100, 200, 300, 400];
let mut states_b: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
let logits_b = forward_batch(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut states_b).unwrap();
let mut lb = vec![0f32; vocab]; logits_b.d2h(&mut lb).unwrap();
let mut states_s: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
let mut ls = vec![0f32; vocab];
for m in 0..b {
let lo = forward_inkling_with_state(&cache, &d, tokens[m], vocab, max_seq, m as i32, 0.0, &mut states_s).unwrap();
lo.d2h(&mut ls).unwrap();
}
let argb = lb.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0;
let args = ls.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0;
let mut max_abs = 0f32; let mut max_rel = 0f32;
for (g, w) in lb.iter().zip(ls.iter()) { max_abs = max_abs.max((g - w).abs()); max_rel = max_rel.max((g - w).abs() / w.abs().max(1.0)); }
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e}");
set_kv_f16(false);
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
assert_eq!(argb, args, "forward_batch argmax must match sequential");
assert!(max_abs < 1e-2, "forward_batch logits parity failed: max_abs={max_abs}");
}
} }