[Core] DSpark brick 3c: target-tap capture in the trunk runner

forward_batch refactored into forward_batch_inner(+optional taps) with thin
forward_batch / forward_batch_taps wrappers (existing signature unchanged).
Captures the 4 DSpark target taps: visit 5 (prelude ip5 entry residual),
visit 23 (core pass1 ip11 entry), visit 41 (core pass2 ip17 entry), and
visit 48 = output-normed final depth mix (model.llm.norm over attn_res_mix).
These feed dspark_context per committed token.
Test forward_batch_taps_capture: logits BIT-IDENTICAL to forward_batch (capture
is pure copies) and tap48 last row unembeds (cast+gemm, no re-norm) to exactly
those logits; all taps finite/nonzero. CPU -D warnings green; ld GPU 55/55.
This commit is contained in:
adm committed 2026-12-02 20:35:55 +01:00
1 parent 0cbec2d847
commit b6ed89b2d2
1 file changed
+78 -1
+78 -1
View File
@@ -1023,6 +1023,25 @@ fn run_layer_batched(
pub fn forward_batch( pub fn forward_batch(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize, cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>], base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, None)
}
/// forward_batch + DSpark target-tap capture: visits 5/23/41 entry residual and
/// visit 48 = output-normed final depth mix. `taps_out[k]` must be [B*hidden] f32.
/// These feed dspark_context (the drafter's committed context) per token.
pub fn forward_batch_taps(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
taps_out: &mut [DeviceBuf; 4],
) -> Result<DeviceBuf, String> {
forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, Some(taps_out))
}
fn forward_batch_inner(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
mut taps: Option<&mut [DeviceBuf; 4]>,
) -> Result<DeviceBuf, String> { ) -> Result<DeviceBuf, String> {
let h = d.hidden; let bu = tokens.len(); let h = d.hidden; let bu = tokens.len();
if bu == 0 { return Err("forward_batch: empty tokens".into()); } if bu == 0 { return Err("forward_batch: empty tokens".into()); }
@@ -1045,7 +1064,12 @@ pub fn forward_batch(
let dpos = DeviceBuf::alloc(bu * 4)?; dpos.h2d_bytes(&pos_bytes)?; let dpos = DeviceBuf::alloc(bu * 4)?; dpos.h2d_bytes(&pos_bytes)?;
let mut blocks = BatchBlocks::new(bu, h, 8)?; let mut blocks = BatchBlocks::new(bu, h, 8)?;
// Prelude. // Prelude.
for ip in 0..6 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; } for ip in 0..6 {
if ip == 5 {
if let Some(t) = taps.as_deref_mut() { vetta_infer_hip::copy_f32(&cur, &t[0], bu * h)?; }
}
run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?;
}
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] prelude {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); } if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] prelude {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
let n_prelude_blocks = blocks.count; let n_prelude_blocks = blocks.count;
let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?; let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?;
@@ -1065,6 +1089,13 @@ pub fn forward_batch(
blocks.truncate(n_prelude_blocks); blocks.truncate(n_prelude_blocks);
} }
for ip in 6..18 { for ip in 6..18 {
let visit = 6 + p * 12 + (ip - 6);
if visit == 23 || visit == 41 {
if let Some(t) = taps.as_deref_mut() {
let k = if visit == 23 { 1 } else { 2 };
vetta_infer_hip::copy_f32(&cur, &t[k], bu * h)?;
}
}
if p > 0 && !no_ctrl { if p > 0 && !no_ctrl {
let mq = cache.msg_queries(ip, h)?; let mq = cache.msg_queries(ip, h)?;
let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?; let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?;
@@ -1084,6 +1115,10 @@ pub fn forward_batch(
let oq = cache.raw("model.llm.attn_res.output_query")?; let oq = cache.raw("model.llm.attn_res.output_query")?;
let mix = DeviceBuf::alloc(bu * h * 4)?; 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)?; vetta_infer_hip::attn_res_mix(&blocks.arena, &cur, &oq, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?;
if let Some(t) = taps.as_deref_mut() {
let onorm = cache.bf16_f32("model.llm.norm.weight")?;
vetta_infer_hip::rms_norm_f32(&mix, Some(&onorm), &t[3], b, h as i32, d.eps)?;
}
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?; 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)?; let logits = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; } if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
@@ -1795,4 +1830,46 @@ mod tests {
// (greedy-vs-reference EXACT) are the blocking production gates. // (greedy-vs-reference EXACT) are the blocking production gates.
assert!(max_abs / gscale < 1e-2, "forward_batch logits parity failed: global_rel={}", max_abs / gscale); assert!(max_abs / gscale < 1e-2, "forward_batch logits parity failed: global_rel={}", max_abs / gscale);
} }
/// DSpark tap capture: forward_batch_taps must (a) leave logits BIT-IDENTICAL
/// to forward_batch (capture is pure copies) and (b) tap48 = output-normed
/// final mix, whose last row unembeds to exactly those logits.
#[test]
#[ignore]
fn forward_batch_taps_capture() {
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 h = d.hidden;
let tokens: Vec<i32> = vec![100, 200, 300, 400];
let mut st_b: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
let lb_buf = forward_batch(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_b).unwrap();
let mut lb = vec![0f32; vocab]; lb_buf.d2h(&mut lb).unwrap();
let mut st_t: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
let mut taps: [DeviceBuf; 4] = std::array::from_fn(|_| DeviceBuf::alloc(b * h * 4).unwrap());
let lt_buf = forward_batch_taps(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_t, &mut taps).unwrap();
let mut lt = vec![0f32; vocab]; lt_buf.d2h(&mut lt).unwrap();
assert_eq!(lb, lt, "tap capture must not perturb logits");
let last = DeviceBuf::alloc(h * 4).unwrap();
vetta_infer_hip::copy_f32_sub(&taps[3], (b - 1) * h, &last, h).unwrap();
// tap48 is ALREADY output-normed, so unembed it directly (cast bf16 +
// gemm), NOT via unembed_logits (which would norm a second time).
let nb = DeviceBuf::alloc(h * 2).unwrap();
vetta_infer_hip::cast_f32_bf16(&last, &nb, h).unwrap();
let unembed = cache.raw("model.llm.unembed.weight").unwrap();
let lo = DeviceBuf::alloc(vocab * 4).unwrap();
vetta_infer_hip::gemm_bf16(&nb, &unembed, &lo, 1, vocab as i32, h as i32).unwrap();
let mut l48 = vec![0f32; vocab]; lo.d2h(&mut l48).unwrap();
assert_eq!(lt, l48, "tap48 (output-normed mix) must reproduce logits");
for k in 0..4 {
let mut v = vec![0f32; b * h]; taps[k].d2h(&mut v).unwrap();
assert!(v.iter().all(|x| x.is_finite()), "tap{k} non-finite");
assert!(v.iter().any(|x| *x != 0.0), "tap{k} all zero");
}
eprintln!("forward_batch_taps: logits bit-identical, tap48 reproduces logits, taps finite");
set_kv_f16(false);
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
}
} }